Set Interface in Java Collections

Introduction

In our previous articles we have seen about Collection interface in Java collections.In this lesson we are going to discuss about Set interface.

Set Interface

A Set is a Collection that will not allow duplicate elements.Set interface is extended from the Collection interface and does not contain any extra methods.It is as same as Collection interface except that Set will not allow any duplicates.There are three types of implementations available in Java platform as shown below.

  • HashSet
  • TreeSet
  • LinkedHashSet

HashSet 

HashSet is a set which stores the elements in a hash table and iterates in an order.

TreeSet

TreeSet is a set which stores the elements in a tree structure based on values of elements.It's traversal is a little bit slower than Hashset.

LinkedHashSet

It is as same as Hashset except with a linked list running through it and  orders in insertion-order.

The following example explains Set in a clear picture.We have a collection c ,  and we need to create the same collection without duplicates.

Initially
 Collection<E> c=new Collection<E>();
To remove duplicates
Collection<E> nodup=new HashSet<E>(c);
If we want the same order originally it was inserted
 Collection<E> nodup=new LinkedHashSet<E>(C);

Conclusion

All operations on Set are same as Collection and nothing beyond the Collection Interface


PREVIOUS                                                                                                                                   NEXT


0 comments:

Post a Comment