HashSet and LinkedHashSet

HashSet implements Set:-
 
This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
// create a hash set
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}
The following is the output from this program:
[F, E, D, C, B, A]

LinkedHashSet extends HashSet implements Set:-

Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set.

import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

public class LinkedHashSetTest {

    public static void main(String[] args) {
        LinkedHashSet obj = new LinkedHashSet();

        obj.add("Hello234");
        obj.add("Hello454");
        obj.add("Hello564");

        Set e = obj;

        for (Iterator i = e.iterator(); i.hasNext();) {
            System.out.println(i.next().toString());

        }

    }
}

Running the code produces the following output:

Hello234
Hello454
Hello564
From the output it is clear the order in which you have added in the code has been output

People who read this post also read :



0 comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More