简体   繁体   中英

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

I am really confused over the implementation of hashcode() and equals() method. 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?

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?

this == obj checks whether the current Object is the SAME Object as the other one.

If they are the same Object, of course they are also "equal" .

compareToIgnoreCase compares two String objects, ignoring the upper-case/lower-case differences :

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.

So when you sort a list of Employee with your custom comparator :

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.

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. 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.

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. For Example, this.equals(obj) will return true if and only if it satisfies the condition in the equals() method.

Since, you have overridden the hashCode() method, the hash code calculation will be done by your overridden method.

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.

Doubt2: what does that compareToIgnoreCase() means? is it going to compare two adjusent objects from List<> or something else is happening, what does it do internally?

This is just normal String comparison of the members of two object. In this case it will comapre the name member of the Employee object for Employee a and Employee b.

Unlike compareTo() , compareToIgnoreCase() makes a case insensitive comparison and will return true even if the case of two strings are not same. For Example,

fooBar
FooBAR

Here, compareTo() will return false but compareToIgnoreCase() will return true .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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