美文网首页工作生活
6.Java----比较器

6.Java----比较器

作者: _麻辣香锅不要辣 | 来源:发表于2019-07-15 16:28 被阅读0次
    简介

    Comparable和Comparator接口都是为了对类进行比较,众所周知,诸如Integer,double等基本数据类型,java可以对他们进行比较,而对于类的比较,需要人工定义比较用到的字段比较逻辑。可以把Comparable理解为内部比较器,而Comparator是外部比较器,基本的写法如下:

    Comparable(实现Comparable接口,并重写CompareTo方法)
    public class ComparableTest {
        @Test
        public void test1(){
            Person[] pList = new Person[]{
                    new Person("test1",11),
                    new Person("test2",55),
                    new Person("test3",33)
            };
            System.out.println(Arrays.toString(pList));
            Arrays.sort(pList);
            System.out.println(Arrays.toString(pList));
        }
    
       
    
    class Person implements Comparable{
        private String name;
        private int age;
    
        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public int compareTo(Object o) {
            if(o instanceof Person){
                Person p = (Person)o;
                if(this.age > p.age)
                {
                    return 1;
                }else if(this.age < p.age){
                    return -1;
                }else{
                    return 0;
                }
            }
            throw new RuntimeException("类型不正确");
        }
    }
    
    Comparator(生成一个Comparator对象,并重写compare方法)
     @Test
        public void test2(){
            Person[] pList = new Person[]{
                    new Person("test1",11),
                    new Person("test2",55),
                    new Person("test3",33)
            };
            System.out.println(Arrays.toString(pList));
            Arrays.sort(pList, new Comparator<Person>() {
                @Override
                public int compare(Person o1, Person o2) {
                    if(o1.getAge() > o2.getAge()){
                        return -1;
                    }else if(o1.getAge() < o2.getAge()){
                        return 1;
                    }else{
                        return 0;
                    }
                }
            });
            System.out.println(Arrays.toString(pList));
    
        }
    }
    

    相关文章

      网友评论

        本文标题:6.Java----比较器

        本文链接:https://www.haomeiwen.com/subject/qnvxhctx.html