hashCode()、equals()以及compareTo()方法的理解
来源:互联网 发布:dns劫持后的域名来路 编辑:程序博客网 时间:2024/04/26 19:37
hashCode()、equals()以及compareTo()方法的理解
(2010-12-28 13:15:30)hashcode
equals
compareto
分类:JAVA技术
1、如果hashcode不相等,则表明两个对象不相等。
2、如果hashcode相等,继续调用equals方法进行判断
所以,要求程序员在重写hashCode方法时尽量做到:不一样的对象,hashCode不一样,这样在判断两个对象是否是同一对象时可以提高效率。
根据这两点,我们可以看一道常见的JAVA面试题:
题目:对于两个对象A、B,A.equals(B)==true,不一定有相同的hashCode(); 这句话是错误的。
当然你自己定义的对象可以实现equals相同而hashCode不同(并不会报错,不知道JAVA为什么不限死),但java的Object类中规定相同的对象一定要有相同的hashCode:原话如下:
Note that it is generally necessary tooverride thehashCode method whenever this method isoverridden, so as to maintain the general contract for thehashCode method, which states that equal objects must haveequal hash codes.
compareTo()方法和equals()方法的关系:
对于某些对象如集合(TreeSet)需要实现内部排序,所以要实现Comparable接口,从而要实现里面的唯一方法compareTo();实现Comparable接口的对象表明遵循自然排序。从Comparable的API中可以看出:
It is strongly recommended (though notrequired) that natural orderings be consistent with equals. This isso because sorted sets (and sortedmaps) without explicitcomparators behave "strangely" when they are used with elements (orkeys) whose natural ordering is inconsistent with equals. Inparticular, such a sorted set (or sorted map) violates the generalcontract for set (or map), which is defined in terms of theequals method.
- hashCode()、equals()以及compareTo()方法的理解
- hashCode()、equals()以及compareTo()方法的理解
- hashCode()、equals()以及compareTo()方法的理解
- hashCode()、equals()以及compareTo()方法的理解
- hashCode()、equals()以及compareTo()方法的理解
- hashCode()、equals()以及compareTo()方法的理解 (整理)
- hashCode()、equals()以及compareTo()方法的理解 (整理)
- 关于重写equals,hashcode以及compareTo方法!
- 关于重写equals,hashcode以及compareTo方法!
- 关于重写equals,hashcode以及compareTo方法!
- 关于重写equals,hashcode以及compareTo方法!
- 关于重写equals,hashcode以及compareTo方法
- 关于重写equals,hashcode以及compareTo方法
- 重写equals,hashcode以及compareTo方法
- 关于重写equals,hashcode以及compareTo方法
- equals、compareTo、hashcode方法
- equals,hashCode,compareTo的重写
- equals、compareTo、hashCode()的区别
- Best Time to Buy and Sell Stock
- 在cocos2dx中的点击事件
- Python模块学习 之zipfile zip文件操作
- 如何实现广度优先遍历(BFS)
- 求n个数的子集的三种思路
- hashCode()、equals()以及compareTo()方法的理解
- splash界面代码
- Codeforces Round #269 (Div. 2) B. MUH and Important Things
- sgu107:987654321 problem
- myeclipse debug模式提示 source not found
- ACM-高精度数
- 对java中equals和hashCode函数的一些理解
- 如何学习一门新的编程语言
- HDU-2844-Coins(多重背包)