简体   繁体   中英

How can I know the sort order of a class implementing Comparable<> without actually running the code?

I have the following example and I would like to know if there is a way to tell in which order, ascending or descending, the movie arrray gets sorted just by looking at the compareTo() method WITHOUT running the code and doing trial and error.

The movie class:

 package com.company;

public class Movie implements Comparable<Movie>  {
    private double rating;
    private String name;
    private int year;

    // Used to sort movies by year
    public int compareTo(Movie m)
    {
        if (this.year == m.year) {
            return 0;
        }

        else if (this.year > m.year) {
            return 1;
        }

        return -1;

    }

    // Constructor
    public Movie(String nm, double rt, int yr)
    {
        this.name = nm;
        this.rating = rt;
        this.year = yr;
    }


}

The main class:

package com.company;

import java.util.*;

public class Main {

    public static void main(String[] args) {
        ArrayList<Movie> list = new ArrayList<Movie>();
        list.add(new Movie("Force Awakens", 8.3, 2015));
        list.add(new Movie("Star Wars", 8.7, 1977));
        list.add(new Movie("Empire Strikes Back", 8.8, 1980));
        list.add(new Movie("Return of the Jedi", 8.4, 1983));

        Collections.sort(list);

        System.out.println("Movies after sorting : ");
        for (Movie movie: list)
        {
            System.out.println(movie.getName() + " " +
                    movie.getRating() + " " +
                    movie.getYear());
        }
    }
}

Result:

Movies after sorting : 
Star Wars 8.7 1977
Empire Strikes Back 8.8 1980
Return of the Jedi 8.4 1983
Force Awakens 8.3 2015

You can read the Javadoc of Comparable 's compareTo and find out that it returns:

a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

In your case, you return a negative value (-1) if this object has a smaller year than that of the other object, 0 if the years are equal and a positive value (1) if this object has a larger year than that of the other object.

Hence one Movie is considered "less than" another Movie if it has a smaller value of the year property.

Therefore your compareTo will sort the Movie s in ascending order of the years, since Collections.sort(List<T> list) :

Sorts the specified list into ascending order, according to the Comparable natural ordering of its elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM