Gaurav Seth
Gaurav Seth

Reputation: 205

Java - Why hash and key in HashMap are final

In java, HashMap internally uses Node<K,V> that implements Map.Entry<K,V> and has the following structure:

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

I want to know why hash and key are final and value and next not?

Upvotes: 1

Views: 1018

Answers (3)

Gaurav Seth
Gaurav Seth

Reputation: 205

It has something to deal with re-hashing. But, I am not very sure how.

Upvotes: -1

sakura
sakura

Reputation: 2279

hash - This is final as once node is created with an hash value it should not change even accidentally.

key - Just making hash as final doesn't make sense, as hash is based on key. So, both hash and key should be final for obvious reasons.

value - value in a node can always change, so no point making it final.

next - this is just a pointer and in a hashmap data structure next can point to different map entry, as it grows (insert/delete) or restructured (rehashing). So again no point making it final. But remember, the key a node/entry contains will never change.

Upvotes: 3

Andy Turner
Andy Turner

Reputation: 140319

The hash and the key define where this Node will be located within the HashMap's data structure, so it is important that these can't be changed once the Node is inserted, in order that the Node can be found again.

The actual value stored is irrelevant from the HashMap's point of view; I guess it might be a slight optimization not to need to create a new Node if you change the value associated with a key.

The next node can change if you add/remove elements from the map.

Upvotes: 2

Related Questions