supreeth v
supreeth v

Reputation: 19

Working of == in the Comparable interface used in ArrayList

Working of == operator in Comparable Interface

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);
     }
  }

}

Please let me how does == operator work

Output

Employee name   Aizzz,41
Employee name    Aisu,31
Employee name    Ganesh,21
Employee name    Vijay,31
Employee name    Supreeth,21

Thank You In Advance

Upvotes: 1

Views: 77

Answers (1)

aioobe
aioobe

Reputation: 421180

The contract of compareTo says:

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

So, when using it like this:

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

it doesn't work at all, because you may have both

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

and

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

which is a violation of the contract. This means that "all bets are off" and any method taking advantage of compareTo (such as Collections.sort) has undefined behavior.

You can use == but you'll have to take better care of the != case:

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

A better way however is to do

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

Upvotes: 6

Related Questions