| Character | HashSet doesn’t follow any order and doesn’t ensure that the order we inserted elements do we get the elements in the same order. | In TreeSet it follows the natural ordering of the elements |
| Null operation | HashSet permits null values | TreeSet doesn’t allow any null values, if it found then its throws null pointer exception |
| Speed | HashSet provides constant time to perform all the basic operation on elements such as search insert, remove, its O (1) | TreeSet performance is lower than the HashSet, the time complexity is O(Log(n)) |
| Functionality | HashSet provides basic functionality to perform the operation | TreeSet provides extra functionality such as pollFirst(), pollLast(), first(), last(), ceiling(), lower() |
| Memory Consumption | HashSet doesn’t compare the elements and its SPREAD the elements across the memory ACCORDING to the key. | TreeSet has a better memory management, if TWO entries found near or same Treeset will place in next to each other. |
| Inheritance | HashSet inherit the normal set interface below is the signature implements java.util.Set, java.lang.Cloneable,
| TreeSetimplements navigable Set below is the signature style java.util.NavigableSet, java.lang.Cloneable, java.io.Serializable { |
| Code | import java.util.HashashSet;
class HashashSetProgram{
public static void main (String [] args) {
HashashSet<String>hashSet = new HashashSet<String>();
hashSet.add("Java");
hashSet.add("spring");
hashSet.add("hibernate");
hashSet.add("thread");
hashSet.add("linux");
// Duplicate removed
hashSet.add("spring");
// DISPLAYING HashashSet elements
System.out.println("HashashSet contains: ");
for(String set : hashSet){
System.out.println(set);
}
}
}
| import java.util.TreeSet;
class TreeSetProgram{
public static void main (String [] args) {
// Create a TreeSet
TreeSet<String>treeSet = new TreeSet<String>();
//add elements to TreeSet
treeSet.add("Java");
treeSet.add("linux");
treeSet.add("hibernate");
treeSet.add("spring");
treeSet.add("thread");
// Duplicate removed
treeSet.add("linux");
// Displaying TreeSet elements
System.out.println("TreeSet contains: ");
for(String set : treeSet){
System.out.println(set);
}
}
} |
| Output | Spring Java Thread Java linux | Java Linux Hibernate Spring thread |