Thursday, 1 May 2014

LinkedHashSet( Collection c )

public LinkedHashSet(Collection<? extends E> c)
Constructs a new linked hash set with the same elements as the specified collection. The linked hash set is created with an initial capacity sufficient to hold the elements in the specified collection and the default load factor (0.75).

import java.util.*;

class LinkedHashSetConstructor4{
 public static void main(String args[]){
  LinkedHashSet<Integer> lnkHashSet;
  ArrayList<Integer> arrayList;
  
  arrayList = new ArrayList<> ();
  
  /* Add Elements to arrayList */
  arrayList.add(10);
  arrayList.add(50);
  arrayList.add(-33);
  arrayList.add(987);
  arrayList.add(1);
  arrayList.add(-76);
  
  lnkHashSet = new LinkedHashSet<> (arrayList);
  
  System.out.println("Elements in arrayList");
  System.out.println(arrayList);
  
  System.out.println("Elements in lnkHashSet");
  System.out.println(lnkHashSet);
 }
}

Output
Elements in arrayList
[10, 50, -33, 987, 1, -76]
Elements in lnkHashSet
[10, 50, -33, 987, 1, -76]

1. throws NullPointerException if the specified collection is null
import java.util.*;

class LinkedHashSetConstructor4NullPointer{
 public static void main(String args[]){
 
  LinkedHashSet<Integer> lnkHashSet;
  ArrayList<Integer> arrayList=null;

  lnkHashSet = new LinkedHashSet<> (arrayList);
 }
}

Output
Exception in thread "main" java.lang.NullPointerException
        at java.util.LinkedHashSet.<init>(LinkedHashSet.java:168)
        at LinkedHashSetConstructor4NullPointer.main(LinkedHashSetConstructor4NullPointer.java:9)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment