什么问题/陷阱,必须重写时,必须考虑equals和hashCode?
我有一个List将随时间更改的值,我想将其与时间值一起存储,并检查是否List再次出现该值。
例如:
[1, 2, 3] is same as [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
我认为既然List<Integer>是通过参考值传递的,所以我认为应该将键字符串化以使用。
例如:
Map<String, Integer> = new HashMap<>()
(key:"stringified key", value: .....)
Run Code Online (Sandbox Code Playgroud)
但是我发现它Map<List<Integer>, Integer> map = new HashMap<>()也可以工作,但是我不知道它为什么起作用,因为无论列表中的值发生了什么变化,键都应该引用相同的列表。
例如:
(key:[reference to key], value: .....)
List<Integer> testList = new ArrayList<>();
testList.add(0);
map.put(testList, 0);
testList.set(0, 1);
if(map.containsKey(testList))System.out.println("duplicate");
else System.out.println("unique");
Run Code Online (Sandbox Code Playgroud)
上面的结果将打印“唯一”,但我认为应该打印“重复”。为什么以上结果显示了这一点?