Thursday, 1 May 2014

LinkedHashSet (int initialCapacity, float loadFactor)

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

import java.util.*;

class LinkedHashSetConstructor3{
 public static void main(String args[]){
  LinkedHashSet<Integer> lnkHashSet;
  HashSet<Integer> hashSet;
  
  lnkHashSet = new LinkedHashSet<> (10, 0.5f);
  hashSet = new HashSet<> (10, 0.5f);
  
  /* 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, or if the load factor is nonpositive

import java.util.*;

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

Output
Exception in thread "main" java.lang.IllegalArgumentException: Illegal load factor: -1.0
        at java.util.HashMap.<init>(HashMap.java:273)
        at java.util.LinkedHashMap.<init>(LinkedHashMap.java:177)
        at java.util.HashSet.<init>(HashSet.java:159)
        at java.util.LinkedHashSet.<init>(LinkedHashSet.java:134)
        at LinkedHashSetConstructor2IllegalArg.main(LinkedHashSetConstructor2IllegalArg.java:6)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment