Why should a Java class implement comparable?

后端 未结 10 738
忘掉有多难
忘掉有多难 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:26

    Here is a real life sample. Note that String also implements Comparable.

    class Author implements Comparable{
        String firstName;
        String lastName;
    
        @Override
        public int compareTo(Author other){
            // compareTo should return < 0 if this is supposed to be
            // less than other, > 0 if this is supposed to be greater than 
            // other and 0 if they are supposed to be equal
            int last = this.lastName.compareTo(other.lastName);
            return last == 0 ? this.firstName.compareTo(other.firstName) : last;
        }
    }
    

    later..

    /**
     * List the authors. Sort them by name so it will look good.
     */
    public List listAuthors(){
        List authors = readAuthorsFromFileOrSomething();
        Collections.sort(authors);
        return authors;
    }
    
    /**
     * List unique authors. Sort them by name so it will look good.
     */
    public SortedSet listUniqueAuthors(){
        List authors = readAuthorsFromFileOrSomething();
        return new TreeSet(authors);
    }
    

提交回复
热议问题