Posts

Showing posts with the label TreeSet

Java TreeSet and HashSet similarities and differences

Java TreeSet and HashSet are implementations of the Set interface. Often you may have wondered, whether to choose HashSet or TreeSet and which is faster. In this article, I will be comparing the HashSet and TreeSet classes in Java. HashSet and TreeSet Similarities Duplicates not allowed Since both HashSet and TreeSet implement the Set interface, they do not allow duplicates. So consider the following code: Set<String> hashSet = new HashSet<String>(); hashSet.add("Mango"); hashSet.add("Mango"); Set<String> treeSet = new TreeSet<String>(); treeSet.add("Mango"); treeSet.add("Mango"); System.out.println("Number of elements in Hashset:"+hashSet.size()); System.out.println("Number of elements in Treeset:"+treeSet.size()); When you execute this code, it will print the following output: Number of elements in Hashset:1Number of elements in Treeset:1  Not Thread-Safe Both HashSet and ...