Defining new set java
In Java, a set is a collection of unique elements, which means that it does not allow duplicate values. Here's how you can define a new set in Java:
Using the HashSet
class:
import java.util.HashSet;
public class MySet {
public static void main(String[] args) {
// Create a new set
HashSet<String> mySet = new HashSet<>();
// Add elements to the set
mySet.add("apple");
mySet.add("banana");
mySet.add("orange");
mySet.add("banana"); // duplicate, will be ignored
// Print the set
System.out.println(mySet);
}
}
In this example, we create a new HashSet
object called mySet
and add some elements to it. The HashSet
class uses a hash table to store its elements, which means that it has a fast lookup time and does not allow duplicate values.
Using the TreeSet
class:
import java.util.TreeSet;
public class MySet {
public static void main(String[] args) {
// Create a new set
TreeSet<String> mySet = new TreeSet<>();
// Add elements to the set
mySet.add("apple");
mySet.add("banana");
mySet.add("orange");
mySet.add("banana"); // duplicate, will be ignored
// Print the set
System.out.println(mySet);
}
}
In this example, we create a new TreeSet
object called mySet
and add some elements to it. The TreeSet
class uses a tree data structure to store its elements, which means that it is sorted by default and does not allow duplicate values.
Using the LinkedHashSet
class:
import java.util.LinkedHashSet;
public class MySet {
public static void main(String[] args) {
// Create a new set
LinkedHashSet<String> mySet = new LinkedHashSet<>();
// Add elements to the set
mySet.add("apple");
mySet.add("banana");
mySet.add("orange");
mySet.add("banana"); // duplicate, will be ignored
// Print the set
System.out.println(mySet);
}
}
In this example, we create a new LinkedHashSet
object called mySet
and add some elements to it. The LinkedHashSet
class uses a combination of a hash table and a linked list to store its elements, which means that it preserves the order in which elements were added and does not allow duplicate values.
Note that all three classes (HashSet
, TreeSet
, and LinkedHashSet
) implement the Set
interface, which means that they share a common set of methods and behavior.