1.

How is the HashSet differ from theTreeSet? What is the use case, were HashSet and Treeset fits?

Answer»

HASHSETTreeSet
CharacterHashSet 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 operationHashSet permits null valuesTreeSet doesn’t allow any null values, if it found then its throws null pointer exception
SpeedHashSet 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))
FunctionalityHashSet provides basic functionality to perform the operationTreeSet provides extra functionality such as pollFirst(), pollLast(), first(), last(), ceiling(), lower()
Memory ConsumptionHashSet 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.
InheritanceHashSet 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 {

Codeimport 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);     }  } }
OutputSpring
Java
Thread
Java
linux
Java
Linux
Hibernate
Spring
thread


Discussion

No Comment Found