Thursday 17 April 2014

HashSet(Collection c)

public HashSet(Collection<? extends E> c)
Constructs a new set containing the elements in the specified collection. The HashMap is created with default load factor (0.75) and an initial capacity sufficient to contain the elements in the specified collection.

import java.util.*;

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

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

1. throws NullPointerException if the specified collection is null

import java.util.*;

class HashSetConstructor4Null{
  public static void main(String args[]){
    HashSet<Integer> mySet1 = null;
  
  HashSet<Integer> mySet2 = new HashSet<> (mySet1);
  
  System.out.println("Elements in mySet2 are " + mySet2);
  }
}

Output
Exception in thread "main" java.lang.NullPointerException
        at java.util.HashSet.<init>(HashSet.java:116)
        at HashSetConstructor4Null.main(HashSetConstructor4Null.java:7)




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment