Why we should use immutable object as a key in HashMap?

I have been asked about why key should be an immutable object on HashMap? I never think about it, but after that question I prepare the answer. When I return to home I check it. Do you know why?

The passed test

package com.devpragmatic;

import org.junit.Test;

import java.util.HashMap;
import java.util.Objects;

import static org.junit.Assert.assertEquals;

public class TestHashMap {

    @Test
    public void hashMapTest(){
        HashMap<NoImmutableClass, String> map = new HashMap<>();
        NoImmutableClass noImmutableObject = new NoImmutableClass();
        noImmutableObject.field = "test1";
        map.put(noImmutableObject, "test1");
        noImmutableObject.field = "test2";
        map.put(noImmutableObject, "test2");
        assertEquals(2, map.size());
    }

    class NoImmutableClass {
        String field;

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof NoImmutableClass)) return false;
            NoImmutableClass that = (NoImmutableClass) o;
            return Objects.equals(field, that.field);
        }

        @Override
        public int hashCode() {
            return Objects.hashCode(field);
        }
    }
}

This is correctly test for HashMap. Such I mentioned, I never think about it, but we should be careful in this case. What happened? The problem is that we have one key twice. We use the same object twice, but its HashCode is changed, so when we use that cached HashMap to compare with new hashCode, that are not equal. We don't change the value, but add new value to map.

Comments

Popular posts from this blog

Why TDD is bad practice?

How correctly imitate dependencies?

Software development using Angular 5 with Spring Boot