Tuesday 3 June 2014

HashMap (int initialCapacity)

HashMap(int initialCapacity)
Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75).

import java.util.*;

class HashMapConstructor2{
  public static void main(String args[]){
    Map<Integer, String> myMap = new HashMap<> (10);
  
  /* Adding Data to myMap */
  myMap.put(1, "First");
  myMap.put(2, "Second");
  myMap.put(3, "Third");
  myMap.put(4, "Fourth");
  
  System.out.println("Elements in myMap are");
  System.out.println(myMap);
  }
}

Output
Elements in myMap are
{1=First, 2=Second, 3=Third, 4=Fourth}

1. Throws IllegalArgumentException if the initial capacity is negative
import java.util.*;

class HashMapConstructor2Illegal{
  public static void main(String args[]){
    Map<Integer, String> myMap = new HashMap<> (-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 HashMapConstructor2Illegal.main(HashMapConstructor2Illegal.java:5)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment