0

I am trying to understand the process that HashSet adds the element.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Test {
    public static void main(String args[]) {
        Set<List<Integer>> set = new HashSet<>();
        List<Integer> list = new ArrayList<>();
        for(int j = 0; j < 3; j++){

            list.add(j);
            System.out.println(list);
            System.out.println(set);
            set.add(list);
            System.out.println(set);
        }
    }
}

So the output is

[0]
[]
[[0]]
[0, 1]
[[0, 1]]
[[0, 1], [0, 1]]
[0, 1, 2]
[[0, 1, 2], [0, 1, 2]]
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

Why does the hashset have 3 same lists? My understanding is hashset will compare every element and the order(https://docs.oracle.com/javase/8/docs/api/java/util/List.html#equals-java.lang.Object-) It should not have 3 same list in the set. Any ideas would be appreciated!

  • Also relevant: https://stackoverflow.com/questions/35444639/altering-hashcode-of-object-inside-of-hashset-hashmap – Progman May 01 '22 at 07:32

0 Answers0