Tuesday, September 24, 2013

LinkedHashSet Example in Java

About LinkedHashSet :
  • LinkedHashSet is class which extends HashSet and Implements Set Interface
  • It maintain insertion order
  • Allows null
  • Contains unique elements Only

If You observe output of LinkedHashSet  example as below, Output is not same in sequence we inserted elements because LinkedHashSet does maintain Insertion Order while HashSet does not.

You may want to refer to :

Java LinkedHashset Example :
package com.anuj.basic;

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

/**
 * 
 * @author Anuj
 * maintain insertion order
 * store unique elements only
 */
public class LinkedHashSetOperations {

 public static void main(String[] args) {
  LinkedHashSet hashSet = new LinkedHashSet();
  
  hashSet.add("Anuj");
  hashSet.add("Zvika");
  hashSet.add("David");
  hashSet.add("David");
  hashSet.add(null);
  
  Iterator iterator = hashSet.iterator();
  while(iterator.hasNext()){
   System.out.println(iterator.next());
  }
 }

}

Output :
Anuj
Zvika
David
null

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

No comments:

Post a Comment