Java中的HashMap和HashSet size()

get*_*one 0 java hashmap hashset

我试图找到有关它的信息但失败了.

如何size()进行HashMapHashSet实施?它是如何工作的?是手术O(1)还是O(n)手术?

Era*_*ran 6

这需要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;
}
Run Code Online (Sandbox Code Playgroud)

HashSetsize()支持的呼吁HashMap.