- Java code
public class ValuePair { public int a = 4,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(){ //请选择下边的答案(多选) } }
A。return 0;
B. return a;
C. return a+b;
D. return a-b;
E. return a^b;
F. return (a<<16)|b;
请说明理由。
根据一般约定,如果2个对象 equals 比较为true,那么hashCode也最好(不是必须)相同。
如果2个对象 equals 比如为false,那么hashCode也最好(不是必须)不同
因此对于这个题目,如果从纯语法层面考虑,全部都是可选的
但是从程序运行效率来看,最好是该hashCode里,a,b值可以互换,而又尽可能做到不同的a,b值返回不同的值。因为C,E最好.
A。return 0; 效率太低
B. return a; 不满足a,b的互换性
D. return a-b; 不满足a,b的互换性
F. return (a < <16)|b; 不满足a,b的互换性
另外,比如 a * b 也满足互换性,但是效率稍低,毕竟没加法和位运算快
* Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
* If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
* It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.