java.lang.IllegalArgumentException in setting capacity of Hashmap in java


In this Example we are going to understand the exceptions while Giving the capacity for Hashmap.

Error Message :
Exception in thread "main" java.lang.IllegalArgumentException: Illegal initial capacity: -6
       at java.base/java.util.HashMap.<init>(HashMap.java:444)
       at java.base/java.util.HashMap.<init>(HashMap.java:463)
       at com.si.hashmap.computeHashMap.main(computeHashMap.java:11)


Error Description :

package com.si.hashmap;

import java.util.HashMap;
import java.util.Map;

public class computeHashMap {
       static Map<String,String> map ;

       public static void main(String[] args) {
              int capacity = -5;
              Map<String,String> mp = new HashMap<String, String>((int) Math.ceil(capacity/0.75));
       }
}
In the above example ,the red background color line is giving the exception.
The number of buckets in the hashmap is called its capacity.The default capacity is 16 for hashmap at creation time.When you try to set hashmap capacity is negative number then we ll get this kind of exception.

Solution:

We can do negative number check before setting the capacity to the HashMap.
With this we can avoid this kind of exceptions.

package com.si.hashmap;

import java.util.HashMap;
import java.util.Map;

public class computeHashMap {
                          static Map<String,String> map ;

                          public static void main(String[] args) {
                           int capacity = -5;
                           if(capacity>0) {
                           Map<String,String> mp = new HashMap<String, String>((int) Math.ceil(capacity/0.75));
                           }else {
                                  System.out.println("Please set capacity as postive number");
                           }
                          }
}
                         
Output:
Please set capacity as postive number
 
Share this post :

Post a comment

Please share your valuable feedback and share this article in social media.

 
Support : Ranga Rajesh Kumar
Copyright © 2019. Error Solution - All Rights Reserved
Site Designed by Ranga Rajesh Kumar