Comparator : Equals method functionality

Viewed 15609

Actually i am going through one of the tutorial in which it mentioned that when we need to implement the Comparator interface we can override equals method. however it is not necessary to override.

So just to understand better, I override the method as follows:

Test.java

 import java.util.TreeSet;

public class Test
{
    public static void main(String[] args)
    {
        TreeSet t = new TreeSet(new MyComparator());
        t.add(1);
        t.add(1);
        t.add(2);
        System.out.println(t);
    }
}

MyComparator.java

import java.util.Comparator;

public class MyComparator
    implements Comparator
{
    @Override
    public int compare(Object o1, Object o2)
    {
        Integer i1 = (Integer) o1;
        Integer i2 = (Integer) o2;
        return i1.compareTo(i2);
    }

    @Override
    public boolean equals(Object o1)
    {
        return false;
    }
}

For other scenario

import java.util.Comparator;

public class MyComparator
    implements Comparator
{
    @Override
    public int compare(Object o1, Object o2)
    {
        Integer i1 = (Integer) o1;
        Integer i2 = (Integer) o2;
        return i1.compareTo(i2);
    }

    @Override
    public boolean equals(Object o1)
    {
        return true;
    }
}

No matter what I return from equals method either true or false .. it is returning the same TreeSet value.

Can anyone can clear up the concept of functionality of equals method please?

7 Answers

The equals method is used to check the Equality of two comparators i.e in equals method you can specify what makes ComparatorA and ComparatorB Identical, it has nothing to do with the elements that are sorted using these comparators.

you don't need to sort the values of Treeset. TreesSet elements are automatically sorted in ascending order.

class TreeSet1{  
   public static void main(String args[]){  
       //Creating and adding elements  
        TreeSet<String> al=new TreeSet<String>();  
        al.add("Ravi");  
        al.add("Vijay");  
        al.add("Ravi");  
        al.add("Ajay");  
        //Traversing elements  
       Iterator<String> itr=al.iterator();  
          while(itr.hasNext()){  
             System.out.println(itr.next());  
          }  
    }  

}

output= Ajay Ravi Vijay

Related