我试图查找有关它的信息但失败了。
HashMap
或 HashSet
中的 size()
是如何实现的?它是如何工作的?它是一个O(1)
还是O(n)
操作?
最佳答案
需要O(1)
时间。 HashMap
有一个 size
实例变量,当添加或删除条目时该变量会被修改:
这是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
调用支持 HashMap
的 size()
。
关于java - Java 中的 HashMap 和 HashSet size(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48443184/