简体   繁体   English

equals(),hashcode()和compare()方法真正发生了什么?

[英]What really happens inside equals(), hashcode() and compare() method?

I am really confused over the implementation of hashcode() and equals() method. 我对hashcode()和equals()方法的实现感到非常困惑。 Here is peace of code. 这是和平的代码。

class Employee {

      int id;
      String name;

      public Employee(int id, String name) {
          super();
          this.id = id;
          this.name = name;
      }

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

      @Override
      public boolean equals(Object obj) {
        Employee other = (Employee) obj;

              if (this == obj)
                    return true;

              if (obj == null)
                    return false;
              if (getClass() != obj.getClass())
                return false;

              if (id != other.id)
                return false;
              if (name == null) {
                if (other.name != null)
                            return false;
                } else if (!name.equals(other.name))
                          return false;
                return true;
        }

    }

[edit 1] Doubt1 : what every comparision really mean? [编辑1] 怀疑 1:每个比较的真正含义是什么?

Now I have implemented comparator interface and its method. 现在,我已经实现了比较器接口及其方法。

  class EmpNameComparator implements Comparator<Employee> {
        @Override
       public int compare(Employee a, Employee b) {
              return a.name.compareToIgnoreCase(b.name);
       }
  }

[edit 2] Doubt2: is it going to compare two adjusent objects from List<> or something else is happening, what does it do internally? [edit 2] 怀疑 2 是要比较List <>中的两个辅助对象还是发生其他事情,它在内部做什么?

this == obj checks whether the current Object is the SAME Object as the other one. this == obj检查当前对象是否与另一个对象相同

If they are the same Object, of course they are also "equal" . 如果它们是相同的对象,那么它们当然也是“相等的”。

compareToIgnoreCase compares two String objects, ignoring the upper-case/lower-case differences : compareToIgnoreCase比较两个String对象,忽略大写/小写的区别:

Compares two strings lexicographically, ignoring case differences. 按字典顺序比较两个字符串,忽略大小写差异。 This method returns an integer whose sign is that of calling compareTo with normalized versions of the strings where case differences have been eliminated by calling Character.toLowerCase(Character.toUpperCase(character)) on each character. 此方法返回一个整数,其符号是用规范化版本的字符串调用compareTo的字符串,该字符串通过在每个字符上调用Character.toLowerCase(Character.toUpperCase(character))消除了大小写差异。

So when you sort a list of Employee with your custom comparator : 因此,当您使用自定义比较器对Employee列表进行排序时:

Collections.sort(employeeList, new EmpNameComparator());

Two employees having the same name (ignoring different cases), will be considered the same employee for the sorting operation . 具有相同名称(忽略大小写)的两名雇员将被视为同一雇员进行排序操作。

Note that you can't tell if John will appear before joHn , or the opposite. 请注意,您无法确定John是否会出现在joHn之前或相反。

Doubt1 :So what is really happening here, I know this is referred to current to current object, why are we comparing this==obj in equals. 疑点1:所以这里真正发生的是什么,我知道这是指当前对象到当前对象,为什么我们将this == obj比较为相等。 what every comparision really mean? 每个比较的真正含义是什么?

When you do this == obj , you basically check whether the reference of this object and the object under comparison ie obj is same or not. 当您执行this == obj ,基本上检查this对象的参考与正在比较的对象(即obj是否相同。

If you are calling equals() then it is comparing whether this object and the object under comparison ie obj are same or not based on the equals() method overridden by you. 如果您正在调用equals()那么它将根据您重写的equals()方法来比较this对象和被比较的对象(即obj是否相同。 For Example, this.equals(obj) will return true if and only if it satisfies the condition in the equals() method. 例如,仅当满足equals()方法中的条件时, this.equals(obj)才会返回true

Since, you have overridden the hashCode() method, the hash code calculation will be done by your overridden method. 由于您已经覆盖了hashCode()方法,因此哈希代码的计算将由您覆盖的方法完成。

There is a contract between hashCode() and equals() and if you are overriding one then you should override other also or else it is not guaranteed to work as expected. hashCode()equals()之间有一个约定,如果要覆盖一个约定,则还应覆盖另一个约定,否则不能保证按预期工作。

Doubt2: what does that compareToIgnoreCase() means? 疑问2:compareToIgnoreCase()是什么意思? is it going to compare two adjusent objects from List<> or something else is happening, what does it do internally? 是要比较List <>中的两个辅助对象还是发生其他事情,它在内部做什么?

This is just normal String comparison of the members of two object. 这只是两个对象成员的正常String比较。 In this case it will comapre the name member of the Employee object for Employee a and Employee b. 在这种情况下,它将比较Employee a和Employee b的Employee对象的name成员。

Unlike compareTo() , compareToIgnoreCase() makes a case insensitive comparison and will return true even if the case of two strings are not same. compareTo()不同, compareToIgnoreCase()进行不区分大小写的比较,即使两个字符串的大小写不同,也将返回true For Example, 例如,

fooBar
FooBAR

Here, compareTo() will return false but compareToIgnoreCase() will return true . 在这里, compareTo()将返回false但是compareToIgnoreCase()将返回true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM