Comparable 与 Comparator

这两个都能通过Collections.sort或者Arrays.sort对对象进行排序。

Comparable<T>实例

由低到高排序 返回1  

由高到低排序 返回-1

public class Point implements Comparable<Point>

{

       public int x;

       public int y;

        @Override

       public int compareTo(Point o) {

        // TODO Auto-generated method stub

        if(this.x>o.x)

           return 1;

       else if( this.x<o.x)

         return -1;

        return 0;

        }

    }       

}   

Arrays.sort();
Collections.sort();

有时候,我们希望能够分别对Point按x,y进行排序,使用这种方法就不行了,就得使用Comparator<T>接口

    class Point

    {

        public float x;

        public float y;    

    }

    class CompareX implements Comparator<Point>

    {



        @Override

        public int compare(Point o1, Point o2) {

            // TODO Auto-generated method stub

            if(o1.x>o2.x)

                return 1;

            else if(o1.x<o2.x)

                return -1;

            else 

            {

                if(o1.y>o2.y)

                    return 1;

                else if(o1.y<o2.y)

                    return -1;

                return 0;

            }

        }

        

    }

    

    class CompareY implements Comparator<Point>

    {



        @Override

        public int compare(Point o1, Point o2) {

            // TODO Auto-generated method stub

            if(o1.y>o2.y)

                return 1;

            else if(o1.y<o2.y)

                return -1;

            return 0;

        }

        

    }

java.util.Arrays.sort(points,new CompareY());//对Y排序

java.util.Arrays.sort(points,new CompareX());//对X排序

 

你可能感兴趣的:(comparator)