简体   繁体   English

Java中的HashMap和HashSet size()

[英]HashMap & HashSet size() in Java

I tried to find information about it but failed. 我试图找到有关此信息,但失败了。

How is size() in HashMap or HashSet implemented? HashMapHashSet size()如何实现? How does it work? 它是如何工作的? Is it an O(1) or O(n) operation? 它是O(1)还是O(n)运算?

It takes O(1) time. 这需要O(1)时间。 HashMap has a size instance variable that gets modified when entries are added or removed: HashMap有一个size实例变量,在添加或删除条目时会对其进行修改:

This is the HashMap implementation: 这是HashMap实现:

/**
 * Returns the number of key-value mappings in this map.
 *
 * @return the number of key-value mappings in this map
 */
public int size() {
    return size;
}

HashSet calls size() of the backing HashMap . HashSet调用后备HashMap size()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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