简体   繁体   中英

How do we get the initial capacity of a HashSet?

How does HashSet get initial capacity?

import java.util.*;
import java.lang.reflect.Field;
public class Demo
{
   static int getCapacity(ArrayList<?> l) throws Exception
   {
      Field dataField = ArrayList.class.getDeclaredField("elementData");
      dataField.setAccessible(true);
      return ((Object[]) dataField.get(l)).length;
   }
   public static void main(String args[])
   {
      ArrayList a = new ArrayList();
      System.out.println(getCapacity(a));
      HashSet h = new HashSet(); //in case HashSet what we do
      System.out.println(h.capacity());
   }
}

Actually we do not have capacity method in HashSet class. Then how do we get capacity of HashSet ? How can we get initial capacity of HashSet object?

HashSet does not expose that information. You can set the initial capacity yourself if you want (eg, HashSet h = new HashSet(22); ). Thejavadoc indicates that the default capacity is 16 .

Internally, the HashSet is just wrapping a HashMap via the HashSet.map field. I suppose you could use reflection to grab the map field and then interrogate it for the initial capacity. I can't see why you would want to do this though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM