Why does this .equals() code example return quot;falsequot;?(为什么这个.equals()代码示例返回q;Falseq;?)
问题描述
考虑:
class Dog{
int height;
int weight;
String name;
}
public class DogTest {
public static void main(String[] args) {
Dog one = new Dog();
one.height=4;
one.name="fudo";
one.weight =2;
Dog two = new Dog();
two.height=4;
two.name="fudo";
two.weight =2;
if (one.equals(two)){
System.out.println("True");
}
else{
System.out.println("False");
}
}
}
为什么此输出为";False";?如果在Java中默认情况下,即使所有对象具有相同的值,也不是所有对象都相等,那么我如何才能说服Java相信这两个对象实际上是相等的?
好的,即使两只狗的名字、身高、体重相同,一只可能是斑点斗牛犬,另一只可能是斗牛犬,即使它们是同一种族,它们在自然界中也可能总是不同的。
ps:我的理解是,if(one==Two){}我们比较的是它们是否都引用堆上的同一对象,.equals字符串的.equals比较它们是否具有相同顺序的相同字符。
推荐答案
默认情况下,equals方法会说"这是内存中的同一对象吗?"除非您覆盖它。
您没有覆盖它。
行为未更改。
您需要添加如下所示的新方法
public boolean equals(Object o) {
if(o instanceof Dog) {
Dog d = (Dog)(o);
Dog t = this;
return t.height == d.height && t.weight == d.weight && t.name.equals(d.name);
}
return false;
}
Stephan提出了一个很好的观点--永远、永远、永远不实现等于没有hashCode。始终在两者中使用相同的字段。
public int hashCode() {
int hash = name.hashCode();
hash = hash * 31 + weight;
hash = hash * 31 + height;
return hash;
}
这篇关于为什么这个.equals()代码示例返回&q;False&q;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么这个.equals()代码示例返回&q;False&q;?


基础教程推荐
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01