zoukankan      html  css  js  c++  java
  • Comparable<T> 与 Comparator<T>

    这两个都能通过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排序
  • 相关阅读:
    Access-自定义控件TabControl
    Excel公式-求最低价网站名字
    Excel图表-太极图
    Excel图表-"DNA"图
    VB中的GDI编程-2 画笔
    leetcode
    leetcode
    leetcode
    leetcode
    leetcode
  • 原文地址:https://www.cnblogs.com/maydow/p/4559243.html
Copyright © 2011-2022 走看看