java 位运算 hashcode_hashcode面试题

Java codepublic classValuePair {public inta= 4,b;public booleanequals(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 inthashCode(){//请选择下边的答案(多选)} }

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.

posted on 2012-05-30 16:08 zhb8015 阅读(350) 评论(0)  编辑  收藏 所属分类: interview

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值