Thursday, 1 May 2014

LinkedHashSet (int initialCapacity)

public LinkedHashSet(int initialCapacity)
Constructs a new, empty linked hash set with the specified initial capacity and the default load factor.

import java.util.*;

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

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

As You observe the output, Elements in LinkedHashSet are in the order they inserted, where as HashSet is not.

1. throws IllegalArgumentException if the initial capacity is less
than zero.

import java.util.*;

class LinkedHashSetConstructor1IllegalArg{
 public static void main(String args[]){
  LinkedHashSet<Integer> lnkHashSet;  
  lnkHashSet = new LinkedHashSet<> (-1); 
 }
}

Output
Exception in thread "main" java.lang.IllegalArgumentException: Illegal initial apacity: -1
        at java.util.HashMap.<init>(HashMap.java:268)
        at java.util.LinkedHashMap.<init>(LinkedHashMap.java:177)
        at java.util.HashSet.<init>(HashSet.java:159)
        at java.util.LinkedHashSet.<init>(LinkedHashSet.java:146)
        at LinkedHashSetConstructor1IllegalArg.main(LinkedHashSetConstructor1IllegalArg.java:6)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment