给定以下类,哪个是hashCode()方法的正确实现?
class ValuePair {
public int a, b;
public boolean equals(Object other) {
try {
ValuePair o = (ValuePair) other;
return (a == o.a && b == o.b)
|| (a == o.b && b == o.a);
} catch (ClassCastException cce) {
return false;
}
}
public int hashCode() {
//Provide implementation here.
}
}请选出3个正确答案。
A)return 0;
B)return a;
C)return a + b;
D)return a – b;
E)return a ^ b;
F)return (a << 16) | b;
这道题中的hashCode方法的作用是什么?
以及hashCode方法和equals方法有什么联系呢?
class ValuePair {
public int a, b;
public boolean equals(Object other) {
try {
ValuePair o = (ValuePair) other;
return (a == o.a && b == o.b)
|| (a == o.b && b == o.a);
} catch (ClassCastException cce) {
return false;
}
}
public int hashCode() {
//Provide implementation here.
}
}请选出3个正确答案。
A)return 0;
B)return a;
C)return a + b;
D)return a – b;
E)return a ^ b;
F)return (a << 16) | b;
这道题中的hashCode方法的作用是什么?
以及hashCode方法和equals方法有什么联系呢?
hasCode()不同的对象equals()必须返回false。
retrun a*b;或者return a+b
建议楼主稍微学学哈希表的底层实现。
如果楼主不会可以加我。
还有2楼说的对。
并且1楼说的不全对。
应为哈希表底层是:
数组+单向链表实现的。
hashcode算法是将hash值转换成数组下标的。
如果hashcode查找到数组中存在该值。
那么继续在单向链表中查找使用equals查找,
如果找不到那么可以添加元素
这也就是2楼的兄弟为什么说equals相等必须hashcode相等了。就像我们上学时候早晨起来排队
一共有好多班级
每个班级又有好多队。如果每个班级只有一个队。那么你找班级就是横向先找----哈希表中数组 hashcode可以看成是班级编号即数组下表
如果找到班级了,你在继续找你的位置,这里使用equals来匹配
读取equals方法使用的所有字段hash码,然后对它们进行^操作
hasCode()不同的对象equals()必须返回false,hasCode()相同的对象equals()返回值随意。
A C E 。 。 。