简体   繁体   中英

Is map.size() always the same as map.entrySet().size()

Say I have a HashMap:

var h = new HashMap();

my question is, is:

h.size() == h.entrySet().size()

always? (Assuming no concurrency issues).

Assuming no concurrency issues modifying the HashMap , then your expression

h.size() == h.entrySet().size()

will be true . From the source code for HashMap , the method size() :

public int size() {
    return size;
}

where size is an instance variable declared by HashMap .

When you call entrySet() , it returns an instance of a nested class called EntrySet , and its size() method is:

public final int size()                 { return size; }

Note that EntrySet doesn't declare its own size variable; it's returning size from HashMap .

Also note that keySet() and values() similarly return their own nested classes that are defined practically identically.

So, no matter where you call size() , it should return identically, assuming no interference from other threads or other structural modifications between calls.

The source code suggests it is...

final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
    public final int size() {
        return size;
    }
    // rest of code
}

...and my decompiler suggests it as well.

public final int size() {
    return HashMap.this.size;
}

Note that you will (somewhat ironically) get burned by ConcurrentHashMap ; this assumption may not hold due to the fact that any modifications to this class would put the state of the size in flux. Even though this is a thread-safe collection, it's not safe to rely on size() to do any kind of logical control like you would with a HashMap , for instance.

Yes, it's always true because a hashmap is just a list of entries. The difference is in the represented form, but the size is the same. (This answer is based on not modifying the HashMap class)

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