Comparable<T> 与 Comparator<T>

本文详细介绍了Java中如何使用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排序

 

转载于:https://www.cnblogs.com/maydow/p/4559243.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值