Java set
Created By: chatGPT
In Java, a
Set
is a collection that does not allow duplicate elements. It is a part of the Java Collections Framework and is implemented in various classes such as HashSet
, LinkedHashSet
, and TreeSet
. A Set
is useful when you want to maintain a unique collection of items without worrying about their order.import java.util.HashSet;
public class SetExample {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Duplicate, will not be added
System.out.println(set); // Output: [Apple, Banana]
}
}
The HashSet class is the most commonly used implementation of the
Set
interface. It is backed by a hash table, which allows for constant time complexity for basic operations such as add, remove, and contains, making it very efficient for large datasets.import java.util.HashSet;
import java.util.Set;
public class HashSetExample {
public static void main(String[] args) {
Set<Integer> numbers = new HashSet<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(1); // Duplicates are not allowed
System.out.println("Set contains:");
for (Integer number : numbers) {
System.out.println(number);
}
}
}
If you need a
Set
that maintains the insertion order, you can use the LinkedHashSet. It uses a linked list to maintain the order in which elements were added, while also ensuring uniqueness.import java.util.LinkedHashSet;
import java.util.Set;
public class LinkedHashSetExample {
public static void main(String[] args) {
Set<String> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add("Java");
linkedHashSet.add("Python");
linkedHashSet.add("C++");
System.out.println(linkedHashSet); // Output: [Java, Python, C++]
}
}
The TreeSet is another implementation of the
Set
interface which sorts the elements in their natural order or according to a specified comparator. It is based on a Red-Black tree.import java.util.Set;
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
Set<String> treeSet = new TreeSet<>();
treeSet.add("Banana");
treeSet.add("Apple");
treeSet.add("Mango");
System.out.println(treeSet); // Output: [Apple, Banana, Mango]
}
}
In summary, a Set in Java is a powerful data structure that helps manage collections of unique items. Depending on your requirements, you can choose between HashSet, LinkedHashSet, and TreeSet according to whether you need performance or ordering.
public class SetInterfaceSummary {
public static void main(String[] args) {
System.out.println("Choose HashSet for performance, LinkedHashSet for order, TreeSet for sorted elements.");
}
}