在比较Java中的数组时,以下两个语句之间是否有任何区别?
array1.equals(array2);
Arrays.equals(array1, array2);
Run Code Online (Sandbox Code Playgroud)
如果是这样,他们是什么?
将可变对象用作Hashmap键是不好的做法吗?当您尝试使用已修改足以更改其哈希码的密钥从Hashmap检索值时会发生什么?
例如,给定
class Key
{
int a; //mutable field
int b; //mutable field
public int hashcode()
return foo(a, b);
// setters setA and setB omitted for brevity
}
Run Code Online (Sandbox Code Playgroud)
用代码
HashMap<Key, Value> map = new HashMap<Key, Value>();
Key key1 = new Key(0, 0);
map.put(key1, value1); // value1 is an instance of Value
key1.setA(5);
key1.setB(10);
Run Code Online (Sandbox Code Playgroud)
如果我们现在打电话map.get(key1)怎么办?这是安全的还是可取的?或者行为是否依赖于语言?
有以下课程:
public class Member {
private int x;
private long y;
private double d;
public Member(int x, long y, double d) {
this.x = x;
this.y = y;
this.d = d;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = (int) (prime * result + y);
result = (int) (prime * result + Double.doubleToLongBits(d));
return result;
}
@Override
public boolean equals(Object obj) {
if (this …Run Code Online (Sandbox Code Playgroud)