Search code examples
javacomparable

Finding max/min value using Comparable


I have an object class

public class Film implements Comparable<Film>

I'm using Eclipse and would like to know why Film is underlined in red with the error saying:

The type Film must implement the inherited abstract method Comparable<Film>.compareTo<Film>

And now to my main question:

How would I get the max/min user submitted film length and title?

My object class Film has getter and setter methods for the Title of the film and the Length of the film and a toString method. Following this article (#3) I created two more methods in my object class:

public int max(Film maxLength){
    int compareLength = ((Film) maxLength).getLength();

    return this.length - compareLength;
}

public int min(Film minLength){
    int compareLength = ((Film) minLength).getLength();

    return compareLength - this.length;
}

Could I use these to find and print max/min values of the user submitted film lengths?

If so, how?

If not, what is the proper way of doing this?

The test class is as follows:

import java.util.Scanner;
public class test {
    public static void main (String[] args){
        Film[] f = new Film[3];
        Scanner input = new Scanner(System.in);
        for (int i=0;i<3;i++){
            f[i] = new Film(); 

            System.out.println("Enter Film Length:");
            f[i].setLength(input.nextInt());
            input.nextLine();
            System.out.println("Enter Title:");
            f[i].setTitle(input.nextLine());
        }
        input.close();
        for (int i = 0; i < 3; i++) {
            System.out.println(f[i].toString());
        }
    }
}

Solution

  • The Film class implements Comparable<Film>. What this means is that you must implement a method called compareTo() in class Film that will provide an ordering for objects of this class.

    @Override
    public int compareTo(Film that) {
        // Order by film length
        return Integer.compare(this.length, that.length);
    }
    

    If you only need to sort the objects by film length you can just use Arrays.sort():

    Film[] films = new Film[3];
    // put the objects into the array
    Arrays.sort(films);
    

    Then films[0] will contain the film with the shortest length, while the last element will be the film with the longest length.

    If you need to compare by other fields, such as film title, you can create a custom comparator:

    class FilmTitleComparator implements Comparator<Film> {
        public int compare(Film a, Film b) {
            return Integer.compare(a.getTitle().length(), b.getTitle().length());
        }
    }
    

    And pass it to Arrays.sort()

    FilmTitleComparator titleComparator = new FilmTitleComparator();
    Arrays.sort(films, titleComparator);
    

    Then films[0] will contain the film with the shortest title, while the last element will be the film with the longest title.