Thursday 17 April 2014

HashSet (int initialCapacity, float loadFactor)

public HashSet(int initialCapacity, float loadFactor)
Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and the specified load factor.

public HashSet(int initialCapacity, float loadFactor) {
     map = new HashMap<>(initialCapacity, loadFactor);
}

import java.util.*;

class HashSetConstructor3{
  public static void main(String args[]){
         HashSet<Integer> mySet = new HashSet<> (10, 0.5f);
  
  /* Add Elements to HashSet */
  mySet.add(10);
  mySet.add(20);
  mySet.add(30);
  mySet.add(40);
  
  System.out.println("Elements in HashSet are " + mySet);
  }
}

Output
Elements in HashSet are [20, 40, 10, 30]

1. throws IllegalArgumentException if the initial capacity is less than zero, or if the load factor is nonpositive
import java.util.*;

class HashSetConstructor3Illegal{
  public static void main(String args[]){
    HashSet<Integer> mySet = new HashSet<> (10, -1);
  }
}

Output
Exception in thread "main" java.lang.IllegalArgumentException: Illegal load fact
or: -1.0
        at java.util.HashMap.<init>(HashMap.java:273)
        at java.util.HashSet.<init>(HashSet.java:130)
        at HashSetConstructor3Illegal.main(HashSetConstructor3Illegal.java:5)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment