❮ Previous Next ❯

Comparator Interface


The general form is:
public int compare(Object ob1, Object ob2)

here the compare() method having 3 cases, like:
Returns -ve if ob1 have to come before ob2.
Returns +ve, if ob1 have to come after ob2.
Returns 0, if ob1 and ob2 are equal.


public boolean equals()
Example

ComparatorDemo.java
package java8s;
import java.util.*;
class ComparatorDemo {
      public static void main(String[] args) {
           
            TreeSet t=new TreeSet(new MyComparator());
            t.add(90);
            t.add(20);
            t.add(0);
            t.add(50);
            System.out.println(t);
      }
}

class MyComparator implements Comparator
{
      public int compare(Object ob1, Object ob2)
      {
            Integer i1=(Integer)ob1;
            Integer i2=(Integer)ob2;
           
            if(i1<i2)
            {
                  return +1;
            }
            else
                  if(i1>i2)
                  {
                        return -1;
                  }
                  else
                  {
                        return 0;
                  }
      }
}

Output


[90, 50, 20, 0]

❮ Previous Next ❯



  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved