在 ArrayList 中使用的 Comparable 接口中使用 ==

Working of == in the Comparable interface used in ArrayList

可比较接口中 == 运算符的工作方式

Employee.java

class Employee implements Comparable
{
    int id; String name; int age;

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

    public int compareTo(Object obj)
    {
        Employee emp = (Employee)obj;
        if(age==emp.age)
        {
            return 0;
        }
        //else if(age>emp.age)
        //return 1;
        else
            return -1;
    }
}

display_logic.java

import java.util.*;
class display_logic
{
  public static void main(String args[])
  {
     ArrayList al = new ArrayList();
     al.add(new Employee(1,"Supreeth",21));
     al.add(new Employee(2,"Vijay",31));
     al.add(new Employee(3,"Ganesh",21));
     al.add(new Employee(4,"Aisu",31));
     al.add(new Employee(5,"Aizzz",41));
     Collections.sort(al);
     Iterator it = al.iterator();
     while(it.hasNext())
     {
        Employee emp = (Employee)it.next();
        System.out.println("Employee name" +emp.name+ "," +emp.age);
     }
  }

}

请告诉我 == 运算符是如何工作的

输出

员工姓名 Aizzz,41
员工姓名爱素,31
员工姓名 Ganesh,21
员工姓名 Vijay,31
员工姓名 Supreeth,21

提前致谢

compareTo的合同说:

The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y.

所以,当这样使用它时:

Employee emp = (Employee)obj;
if(age==emp.age)
    return 0;
else
    return -1;

根本不起作用,因为你可能两者都有

emp1.compareTo(emp2) == -1      // "emp1 should come before emp2"

emp2.compareTo(emp1) == -1      // "emp2 should come before emp1"

这违反了合同。这意味着 "all bets are off" 和任何利用 compareTo 的方法(例如 Collections.sort)具有未定义的行为。

可以使用==,但您必须更好地照顾!=案例:

Employee emp = (Employee)obj;
if(age==emp.age)
    return 0;
else if (age < emp.age)
    return -1;
else
    return 1;

然而更好的方法是

return Integer.compare(age, emp.age);