What exactly is bucket in hashmap?

后端 未结 4 1993
执念已碎
执念已碎 2020-12-03 02:33

Recently, in an interview I was asked, what exactly is a bucket in hashmap? Whether it is an array or a arraylist or what?

I got confused. I know hashmaps are backe

4条回答
  •  不思量自难忘°
    2020-12-03 03:05

    Buckets exactly is an array of Nodes. So single bucket is an instance of class java.util.HashMap.Node. Each Node is a data structure similar to LinkedList, or may be like a TreeMap (since Java 8), HashMap decides itself what is better for performance--keep buckets as LinkedList or TreeMap. TreeMap will be only chosen in case of poorly designed hashCode() function, when lots of entries will be placed in single bucket. See how buckets look like in HashMap:

    /**
         * The table, initialized on first use, and resized as
         * necessary. When allocated, length is always a power of two.
         * (We also tolerate length zero in some operations to allow
         * bootstrapping mechanics that are currently not needed.)
         */
        transient Node[] table;
    

提交回复
热议问题