Set Collection Tutorial for Java Beginners

Set is a part Java Collection Framework. Set is an Interface in java.util package. It implements Collection Interface.

Important Points related to Set

  • It doesn’t contain duplicate elements.
  • Some Set implementations have restriction on NULL element.

 

Concrete Implementation of Set Interface

  • HashSet
  • LinkedHashSet
  • TreeSet
  • EnumSet

     

Important Method in Set Interface

This Interface doesn’t contain any special method. It inherit all method from Collection Interface only.

 

HashSet

  • This class is part of Java CollectionFramework.
  • This Class implements the Set Interface.
  • It is backed by Hash Table.
  • It is Unordered. (Order is not predictable over time)
  • Constant time performance for basic operation like add, remove, contains and size.
  • It is not synchronized.
  • Iterators returned by Iterator method is FailFast.

 

Constructor

  • HashSet(Collection<? extends E> c) : Constructs a new set containing the elements in the specified collection.
  • HashSet(int initialCapacity, float loadFactor) : Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and the specified load factor.
  • HashSet(int initialCapacity) : Constructs a new, empty set.

 

LinkedHashSet

  • Order of the element is predictable.
  • It maintains doubly link list, running through all of its entries.
  • Order of the element will be the same as order of insertion.
  • It permits NULL values.
  • Like HashSet it provide constant time performance for basic operation.
  • Iteration time over linkedList is size proportional.
  • Initial Capacity and Load Factor decide the performance of LinkedHashSet.
  • It is not synchronized.
  • Iterator returned by the Iterator method of this class is FAIL-FAST.

Constructor

  • LinkedHashSet(int initialCapacity, float loadFactor) : Constructs a new, empty linked hash set with the specified initial capacity and load factor.
  • LinkedHashSet(int initialCapacity) : Constructs a new, empty linked hash set with the specified initial capacity and the default load factor of 0.75.
  • LinkedHashSet() : Constructs a new, empty linked hash set with the default initial capacity of 16 and load factor 0.75.
  • LinkedHashSet(Collection<? extends E> c) : Constructs a new linked hash set with the same elements as the specified collection.

TreeSet

By | 2017-07-09T12:13:58+00:00 February 16th, 2013|Core Java|0 Comments

About the Author:

Leave A Comment