Thursday 17 April 2014

HashSet (int initialCapacity)

Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and default load factor (0.75).

The implementation looks like below.

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

import java.util.*;

class HashSetConstructor2{
  public static void main(String args[]){
         HashSet<Integer> mySet = new HashSet<> (10);
  
  /* 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
import java.util.*;

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

Output
Exception in thread "main" java.lang.IllegalArgumentException: Illegal initial c
apacity: -10
        at java.util.HashMap.<init>(HashMap.java:268)
        at java.util.HashMap.<init>(HashMap.java:297)
        at java.util.HashSet.<init>(HashSet.java:142)
        at HashSetConstructor2Illegal.main(HashSetConstructor2Illegal.java:5)

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment