Skip to main content
  1. About
  2. For Teams
Asked
Viewed 169 times
0

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?

1

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for quick response and sharing the resource.

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.