- 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.