为什么此.equals()代码示例返回"false"? [英] Why this .equals() code example returns "false"?

查看:77
本文介绍了为什么此.equals()代码示例返回"false"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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这两个对象实际上是相等的呢?好吧,即使两只狗的名字,身高,体重都一样,一只可能是达尔马提纳犬,另一只可能是斗牛犬,即使它们是同一种族",从本质上讲,它们也总是可以彼此不同.

Why this outputs "False"? If it is by default in Java that "all objects are not equal even if they have same values" then how can I "persuade" Java that these two objects actually are equal? Okay, even if two dogs have same name, height, weight one could be dalmatiner and the other one pit bull, and even if they are the same "race", in nature, they can always be different from one another.

PS:我了解到,如果说(one == two){},我们正在比较它们是否都指向堆上的同一对象,则字符串的.equals比较它们是否具有相同顺序的相同字符./p>

PS: I understand that by saying if (one==two) {} we are comparing if they both refer to the same object on the heap, .equals on string's compares if they have same characters in the same order.

推荐答案

默认情况下,equals方法显示内存中是否存在相同的对象?"除非您覆盖它.

The equals method by default says "Is this the same object in memory?" unless you override it.

您没有覆盖它.

行为没有改变.

您将要添加一个像这样的新方法

You'll want to add a new method like this

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,实现永远不会等于.始终在两个字段中使用相同的字段.

Stephan brings up a good point - never, ever, ever implment equals without hashCode. Always use the same fields in both.

public int hashCode() {
    int hash = name.hashCode();
    hash = hash * 31 + weight;
    hash = hash * 31 + height;
    return hash;
}

这篇关于为什么此.equals()代码示例返回"false"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆