Wednesday, 20 August 2014

Java Collections -Set

Set a Collection used to store Unordered but unique elements.
If you try to store a duplicat element in a set it will throw an error.

Example of set 

Set setA = new HashSet();

String element = "element 1";

setA.add(element);

System.out.println( set.contains(element) );

Implemenation of set 

Since Set is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following Set implementations in the Java Collections API
1. HashSet
2. EnumSet
3. TreeSet
4. LinkedHashSet
How to reverse a string in java

HashSet: HashSet is backed by a HashMap. It makes no guarantees about the sequence of the elements when you iterate them. 

eg. Set setB = new HashSet();


LinkedHashSet : LinkedHashSet differs from HashSet by guaranteeing that the order of the elements during iteration is the same as the order they were inserted into the LinkedHashSet. 
Reinserting an element that is already in the LinkedHashSet does not change this order.

Set setC = new LinkedHashSet();

TreeSet :TreeSet also guarantees the order of the elements when iterated, but the order is the sorting order of the elements. In other words, the order in which the elements whould be sorted if you used a Collections.sort() on a List or array containing these elements. This order is determined either by their natural order (if they implement Comparable), or by a specific Comparator implementation.
eg :Set setD = new TreeSet();



You may Like :

2 comments: