1

I am adding an ArrayList into a HashMap and then changing the original list as follows:

import java.util.*;

public class HashSetCheck{

    public static void main(String[] args){
        HashMap<ArrayList<Integer>, Integer> set = new HashMap<ArrayList<Integer>, Integer>();
        ArrayList<Integer> check = new ArrayList<Integer>();
        set.put(check, 0);
        check.add(1);
        ArrayList<Integer> sep = new ArrayList<Integer>();
        sep.add(1);
        System.out.println(set.containsKey(check));
        System.out.println(set.containsKey(sep));
    }

}

In both cases, the program prints out false.

I looked at this question, and know that the HashMap is storing the reference as a key. Furthermore, the documentation states that containsKey(key) will check the following condition for all values k inside:

(key==null ? k==null : key.equals(k))

Shouldn't the equals() be true for the first case. It is the same reference, and it is the same value. Otherwise, how is equals() being implemented for an ArrayList?

Abundance
  • 1,529
  • 3
  • 19
  • 40
  • 1
    It's not `equals()` that's important here, it's `hashCode()` which you're changing after putting the key in the map. – Kayaman Jan 12 '18 at 18:26

0 Answers0