Thursday 7 May 2015

Set Classes

Hashset


  • uses hashtable to store the elements.It extends AbstractSet class and implements Set interface.
  • contains unique elements only.

Difference between List and Set 

List can contain duplicate elements whereas Set contains unique elements only.

example,
HashSet<String> hashSet=new HashSet<String>();  
hashSet.add("set 1"); 
hashSet.add("set 2"); 

Iterator<String> itr=al.iterator(); 
while(itr.hasNext()){ 
   System.out.println(itr.next());  
 }  

Output,
set 1
set 2

Linked Hash set,


  • Contains unique elements only like HashSet. It extends HashSet class and implements Set interface.
  • Maintains insertion order.
Example,
LinkedHashSet<String> linkedHashSet=new LinkedHashSet<String>();  

Tree set,

  • contains unique elements only like HashSet. The TreeSet class implements NavigableSet interface that extends the SortedSet interface.
  • maintains ascending order.
TreeSet class hierarchy

Example,
TreeSet<String> al=new TreeSet<String>();  

Differences,


No comments:

Post a Comment