Saturday, 7 January 2012

HashSet

HashSet:
  •  HashSet represents a set of elements (objects)
  •  The underlying data structure is HashTable.
  • Insertion order is not preserved and it is based on hashcode of that objects
  • If we are insert duplicate objects we won't get any compile-time or run-time errors."add()" method simply returns false.
  •  Heterogeneous objects are allowed.
  • Null insertion is possible. 
  • It implements  serializable, clonable interfaces but not RandomAccess.
 Constructors:
  • HashSet h=new HashSet();//creates an empty HashSet object with default  initial capacity 16 and default fill ratio 0.75 .fill ratio is also known as Load Faction
  • HashSet h=new HashSet(int initialcapacity);
  • HashSet h=new HashSet(int initialcapacity,float Fillratio);
HashSetExample
import java.util.HashSet;
import java.util.Iterator;

public class HashSetExample {

  public static void main(String[] args) {

    //create object of HashSet
    HashSet hSet = new HashSet();
  
    //add elements to HashSet object
    hSet.add("a");
    hSet.add("b");
    hSet.add("c");
    hSet.add(null);
    hSet.add("e");
    hSet.add("f");
    hSet.add("a");//duplicate value it return false
    System.out.println(hSet);

    Iterator itr = hSet.iterator();
 System.out.println("displaying elements by using listIterator");
   
    while(itr.hasNext()){
     String s=(String)itr.next();
    System.out.println(s);
}
}
}
    
output:
[f, null, e, b, c, a]
displaying elements by using ListIterator
f
null
e
b
c

a



No comments:

Post a Comment