5

While reading about HashMap I see that it is implemented as an array of buckets? Now are these buckets always linked lists? If so, why are they called buckets and not linked lists?

2
  • 3
    What programming language is this for? Suspecting Java Commented Aug 23, 2013 at 19:54
  • 2
    That kind of assumption has led to a famous DoS attack (bugzilla.redhat.com/show_bug.cgi?id=750521). In retrospect, a linked list was a poor choice of bucket implementation, but Java is not going to change it. Commented Aug 23, 2013 at 20:14

3 Answers 3

6

Looking at the source code of HashMap tells us that it's implemented as an array of Entries:

transient Entry[] table;

Each Entry has a field next, so they create a single linked list structure:

static class Entry<K,V> implements Map.Entry<K,V> {
    final K key;
    V value;
    Entry<K,V> next;

"Bucket" is a higher-level term, used in the literature and when explaining hash maps. Here "buckets" are implemented as a single linked lists.

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

Comments

4

In Java's Hashmap, the buckets are implemented as a linked list (each Entry has a reference to another entry called next).

The term "bucket" is referring to a concept. Linked list an implementation detail.

Comments

0

Java, uses the concept of "Seperate Chaining" where it's implemented as an array of linked lists, in order to avoid collisions. This though, is not always the case. A hashmap can be implemented as an array entirely (linear probing); this though has a higher chance of creating a colission.

Regarding your question of "buckets". You could imagine a linked list as a bucket. However, if your HashMap implementation uses a proper HashFunction (algorithm to distribute your values in the hashmap array), your "buckets" only has, preferably, one item in it.

Comments

Your Answer

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.