I tried to find information about it but failed.
How is size()
in HashMap
or HashSet
implemented? How does it work? Is it an O(1)
or O(n)
operation?
It takes O(1)
time. HashMap
has a size
instance variable that gets modified when entries are added or removed:
This is the HashMap
implementation:
/**
* 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
.
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.