我从Java的HashSet文档中了解到,仅当set包含使用Objects.equals()方法包含指定元素时,.contains()才返回true。我围绕数组实现了一个包装器类,这样Objects.equals()返回true,但是.contains()仍然返回false。为什么会这样?
import java.util.HashSet;
import java.util.Arrays;
import java.util.Objects;
public class MyClass {
static class ArrayWrapper extends Object {
int[] arr;
ArrayWrapper(int[] arr) {
this.arr = arr;
}
@Override
public boolean equals(Object arr) {
if (!(arr instanceof ArrayWrapper)) {
return false;
}
return Arrays.equals(this.arr, ((ArrayWrapper) arr).arr);
}
}
public static void main(String args[]) {
HashSet<ArrayWrapper> set = new HashSet<>();
int[] arr1 = new int[] { 2, 4, 6 };
int[] arr2 = new int[] { 2, 4, 6 };
ArrayWrapper aw1 = new ArrayWrapper(arr1);
ArrayWrapper aw2 = new ArrayWrapper(arr2);
set.add(aw1);
System.out.println(Objects.equals(aw2, aw1)); // true
System.out.println(set.contains(aw2)); // Should be true?
}
}