Why should a Java class implement comparable?

后端 未结 10 770
忘掉有多难
忘掉有多难 2020-11-22 13:14

Why is Java Comparable used? Why would someone implement Comparable in a class? What is a real life example where you need to implement comparable

10条回答
  •  礼貌的吻别
    2020-11-22 13:34

    Comparable is used to compare instances of your class. We can compare instances from many ways that is why we need to implement a method compareTo in order to know how (attributes) we want to compare instances.

    Dog class:

    package test;
    import java.util.Arrays;
    
    public class Main {
    
        public static void main(String[] args) {
            Dog d1 = new Dog("brutus");
            Dog d2 = new Dog("medor");
            Dog d3 = new Dog("ara");
            Dog[] dogs = new Dog[3];
            dogs[0] = d1;
            dogs[1] = d2;
            dogs[2] = d3;
    
            for (int i = 0; i < 3; i++) {
                System.out.println(dogs[i].getName());
            }
            /**
             * Output:
             * brutus
             * medor
             * ara
             */
    
            Arrays.sort(dogs, Dog.NameComparator);
            for (int i = 0; i < 3; i++) {
                System.out.println(dogs[i].getName());
            }
            /**
             * Output:
             * ara
             * medor
             * brutus
             */
    
        }
    }
    

    Main class:

    package test;
    
    import java.util.Arrays;
    
    public class Main {
    
        public static void main(String[] args) {
            Dog d1 = new Dog("brutus");
            Dog d2 = new Dog("medor");
            Dog d3 = new Dog("ara");
            Dog[] dogs = new Dog[3];
            dogs[0] = d1;
            dogs[1] = d2;
            dogs[2] = d3;
    
            for (int i = 0; i < 3; i++) {
                System.out.println(dogs[i].getName());
            }
            /**
             * Output:
             * brutus
             * medor
             * ara
             */
    
            Arrays.sort(dogs, Dog.NameComparator);
            for (int i = 0; i < 3; i++) {
                System.out.println(dogs[i].getName());
            }
            /**
             * Output:
             * ara
             * medor
             * brutus
             */
    
        }
    }
    

    Here is a good example how to use comparable in Java:

    http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html?page=2

提交回复
热议问题