Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

java - A HashMap with default capacity 16 can contain more than 11/16 objects without rehashing - Is this right?

This is a followup question to What is the initial size of Array in HashMap Architecture?.

From that question I understand the initial capacity of HashMap is 16 by default which allows up to 11 entries before resizing since the default load factor is 0.75.

  1. When does the rehashing take place? After 11 entries in the array or 11 entries in one of the linked lists? I think after 11 entries in the array.

  2. Since the array size is 16 a HashMap could contain many objects (maybe more than 16) in a linked list as long as the array size is less than or equal to 11. Hence, a HashMap with default capacity 16 can contain more than 11/16 objects without rehashing - is this right?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Hence, a HashMap with default capacity 16 can contain more than 11/16 objects(K,V) without rehashing

This is an obvious flaw in using the number of buckets occupied as a measure. Another problem is that you would need to maintain both a size and a number of buckets used.

Instead it's the size() which is used so the size() is the only thing which determines when rehashing occurs no matter how it is arranged.

From the source for Java 8

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
    int s = m.size();
    if (s > 0) {
        if (table == null) { // pre-size
            float ft = ((float)s / loadFactor) + 1.0F;
            int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                     (int)ft : MAXIMUM_CAPACITY);
            if (t > threshold)
                threshold = tableSizeFor(t);
        }
        else if (s > threshold)
            resize();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...