zoukankan      html  css  js  c++  java
  • 关于comparable接口

    参考博客: https://blog.csdn.net/nvd11/article/details/27393445

    第一个例子
    @Test
        public void fun1(){
            List list = new ArrayList();
            list.add(1);
            list.add(6);
            list.add(3);
            Collections.sort(list);   //这里将list里面的元素进行了排序(为什么可以排序,因为Integer实现了comparable接口且重写了compareTo方法
                                      //list里面的元素进行比较的时候会调用compareTo方法)
            for (Object object : list) {
                System.out.println(object);
            }
        }

    结果: 1,3,6

    Integer里面的源码: (同样String类中实现了这个接口)
      public int compareTo(Integer anotherInteger) {

         return compare(this.value, anotherInteger.value);
            }

           public static int compare(int x, int y) {

        return (x < y) ? -1 : ((x == y) ? 0 : 1);
           }

    因为实现了comparable接口,所以list里面的元素进行比较的时候就会调用compareTo方法

    compareTo返回 正数 则x > y  

    返回负数 则 x<y

    返回0 则 x = y

    public class Liyong implements Comparable<Liyong> {
        private int avg;
        private String name;
    
        public Liyong() {
            super();
        }
    
        public Liyong(int avg) {
            super();
            this.avg = avg;
        }
        
    
        public Liyong(String name, int avg) {
            super();
            this.avg = avg;
            this.name = name;
        }
        public Liyong(int avg, String name) {
            super();
            this.avg = avg;
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAvg() {
            return avg;
        }
    
        public void setAvg(int avg) {
            this.avg = avg;
        }
    
        @Override
        public int compareTo(Liyong o) {
            return avg - o.getAvg();
        }
    
        @Override
        public String toString() {
            return "Liyong [avg=" + avg + ", name=" + name + "]";
        }
    }
    
    @Test
        public void fun2(){
            List list2 = new ArrayList();
            list2.add(new Liyong("张三", 1));
            list2.add(new Liyong("李四", 6));
            list2.add(new Liyong("王五", 3));
            Collections.sort(list2);   
            for (Object object : list2) {
                System.out.println(object);
            }
        }

    结果:

    Liyong [avg=1, name=张三]
    Liyong [avg=3, name=王五]
    Liyong [avg=6, name=李四]

    如果Liyong类没有实现comparable接口,则会报错 

    java.lang.ClassCastException: com.关于Comparable接口.Liyong cannot be cast to java.lang.Comparable
    at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:320)
    at java.util.ComparableTimSort.sort(ComparableTimSort.java:188)
    at java.util.Arrays.sort(Arrays.java:1312)
    at java.util.Arrays.sort(Arrays.java:1506)
    at java.util.ArrayList.sort(ArrayList.java:1454)
    at java.util.Collections.sort(Collections.java:141)
    at com.关于Comparable接口.TestMain.fun2(TestMain.java:29)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

     实现并重写compareTo方法,且按照自己定义的规则来比较两个对象,从而进行排序

      

  • 相关阅读:
    python-函数(下):递归、高阶函数
    Spring Hystrix 原理与使用详解
    Jmeter 添加kafka支持
    dnspod-sr 高性能DNS 服务器软件
    Jupyter精选资源合集
    spring 跨域CORS Filter
    TensorFlow 基础准备指导
    TortoiseGit SSH-key 免用户名密码验证
    node.js、npm 升级操作详解
    Maven -DskipTests和-Dmaven.test.skip=true的区别
  • 原文地址:https://www.cnblogs.com/liyong888/p/8665488.html
Copyright © 2011-2022 走看看