为什么这两个简单的对象不相等? [英] Why this two simple objects are not equal?

查看:70
本文介绍了为什么这两个简单的对象不相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个学校班级:

public class School {

    private String name;
    private int id;
    private boolean isOpen;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public boolean isOpen() {
        return isOpen;
    }
    public void setOpen(boolean isOpen) {
        this.isOpen = isOpen;
    }
}

然后,我创建了School的两个实例,并比较了两个实例的相等性:

Then I created two instances of School, and compare the equality of the two instances:

public static void main(String[] args) {
        //school1
        School school1 = new School();
        school1.setId(1);
        school1.setName("schoolOne");

        //school2
        School school2 = new School();
        school2.setId(1);
        school2.setName("schoolOne");

            //result is false , why?
        System.out.println("school1 == school2 ? " + school1.equals(school2));

    }

即使我为 school1 &设置了相同的 id name school2 实例,但是 school1.equals(school2)返回false,为什么?

Even though I set the same id and name to school1 & school2 instances, but school1.equals(school2) returns false, why?

推荐答案

您必须覆盖

You have to override the equals(Object) method:

将其放置在您的学校班级中:

Place this in your School class:

@Override
public boolean equals(Object other) {
    if (other == this) return true;
    if (other == null || !(other instanceof School)) return false;
    School school = (School) other;
    if (school.id != this.id) return false;
    if (!(school.name.equals(this.name))) return false;
    if (school.isOpen != this.isOpen) return false;
    if (!(school.hashCode().equals(this.hashCode()))) return false;
    return true;
}

如果要执行此操作,覆盖

If you are going to this, it is also wise to override the hashCode() method as well.

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + (int) id;
    result = prime * result + (name != null ? name.hashCode() : 0);
    result = prime * result + (isOpen ? 0 : 1);
    return result;
}


其他信息

我相信这是覆盖 hashCode()的最好解释.

此答案由 dmeister 发布,用于以下帖子:SO:哈希代码实现 .

This answer was posted by dmeister for the following post: SO: Hash Code implementation.

我一直在引用它,在为给定类生成 hashCode()方法时,似乎在Eclipse中使用了此功能.

I reference this all the time, and it looks like this functionallity is used in Eclipse when generating the hashCode() method for a given class.

在几乎所有情况下都提出了合理的良好实施方案Josh Bloch的项目8中的有效Java".最好的是看它在那里,因为作者在那里解释了为什么这种方法很好.

A for nearly all cases reasonable good implementation was proposed in Josh Bloch's "Effective Java" in item 8. The best thing is to look it up there because the author explains there why the approach is good.

简短版本:

  1. 创建一个int结果并分配一个非零值.

  1. Create a int result and assign a non-zero value.

对于在equals-Method中测试的每个字段,可通过以下方式计算哈希码c:

For every field tested in the equals-Method, calculate a hash code c by:

  • 如果字段f是布尔值:计算(f?0:1);
  • 如果字段f是字节,char,short或int:计算(int)f ;
  • 如果字段f长:计算(int)(f ^(f>>> 32));
  • 如果字段f是浮点型:计算 Float.floatToIntBits(f);
  • 如果字段f是双精度型:计算 Double.doubleToLongBits(f)并像处理每个long值一样处理返回值;
  • 如果字段f是对象:使用 hashCode()方法的结果,或者如果 f == null ;
  • 如果字段f是数组:将每个字段视为单独的元素,并将以递归的方式计算哈希值并组合这些值如下所述.

  • If the field f is a boolean: calculate (f ? 0 : 1);
  • If the field f is a byte, char, short or int: calculate (int)f;
  • If the field f is a long: calculate (int)(f ^ (f >>> 32));
  • If the field f is a float: calculate Float.floatToIntBits(f);
  • If the field f is a double: calculate Double.doubleToLongBits(f) and handle the return value like every long value;
  • If the field f is an object: Use the result of the hashCode() method or 0 if f == null;
  • If the field f is an array: See every field as separate element and calculate the hash value in a recursive fashion and combine the values as described next.

将散列值c与结果组合在一起:

Combine the hash value c with result with:

结果= 37 *结果+ c

返回结果

对于大多数使用情况,这应该导致哈希值的正确分配.

This should result in a proper distribution of hash values for most use situations.

这篇关于为什么这两个简单的对象不相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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