使用 Comparable 查找 max/min 值

Finding max/min value using Comparable

我有一个objectclass

public class Film implements Comparable<Film>

我正在使用 Eclipse,想知道为什么 Film 带有红色下划线并显示错误消息:

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

现在我的主要问题是:

如何获得 max/min 用户提交的电影长度和标题?

我的 object class 电影有 getter 和 setter 电影标题和电影长度的方法以及 toString 方法。在 this 文章 (#3) 之后,我在 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;
}

我可以使用这些来查找和打印用户提交的电影长度的 max/min 值吗?

如果是,怎么做?

如果不是,正确的做法是什么?

测试class如下:

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());
        }
    }
}

为简单起见,我将您的 Film class 存根以显示如何实现 Comparable

的简单示例
public class Film implements Comparable<Film> {
    int maxLength;
    int minLength;
    String title;

    public Film() {
         this.maxLength = 0;
         this.minLength = 0;
         this.title = "";
    }    

    // implement this method to accomplish comparison
    public int compareTo(Film f) {
        int result = 0; // the result to compute.

        if ( this.equals(f) ) {
            result = 0; // these objects are actually equal
        }

        // compare using meaningful data
        else if ( f != null) {
            // check to see if this film is greater than the specified film
            if ( this.getMaxLength() > f.getMaxLength() ) {
                // this film is comparatively greater, return > 0
                result = 1;
            }
            else if ( this.getMaxLength() == f.getMaxLength() ) {
                // these two films are comparatively equal
                result = 0;
            }
            else {
                // this film is comparatively less than the specified film
                result = -1;
            }

            // similarly, you could also check min, but there's really no reason to do that unless your implementation calls for it.
        }
        else {
            throw new IllegalArgumentException("null Film object not allowed here...");
        }

        return result;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Film film = (Film) o;

        if (maxLength != film.maxLength) return false;
        if (minLength != film.minLength) return false;
        if (!title.equals(film.title)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = maxLength;
        result = 31 * result + minLength;
        result = 31 * result + title.hashCode();
        return result;
    }

    public int getMaxLength() {
        return maxLength;
    }

    public void setMaxLength(int maxLength) {
        this.maxLength = maxLength;
    }

    public int getMinLength() {
        return minLength;
    }

    public void setMinLength(int minLength) {
        this.minLength = minLength;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }    
}

要修复你的测试以实际使用这样的实现(它并没有真正测试任何东西......),你可以这样做:

import java.util.Scanner;
public class test {
    public static void main (String[] args){
        Film lastFilm = null; // arbitrary reference to film
        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++) {
            if ( lastFilm != null ) {
                 // compare the films to test. current to last film
                 if ( f[i].compareTo(lastFilm) > 0 ) {
                     System.out.println(f[i].getTitle() + " is greater than " + lastFilm.getTitle()");
                 }
                 else if ( f[i].compareTo(lastFilm) < 0 ) {
                     System.out.println(f[i].getTitle() + " is less than " + lastFilm.getTitle()");
                 }
                 else {
                     System.out.println(f[i].getTitle() + " is equal to " + lastFilm.getTitle()");
                 }
            }
            System.out.println(f[i].toString());
            lastFilm = f[i];
        }
    }
}

这样的事情可以让你开始......祝你好运

Film class 实现 Comparable<Film>。这意味着您必须在 class Film 中实现一个名为 compareTo() 的方法,该方法将为 class 的 objects 提供排序。

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

如果您只需要按电影长度对 objects 进行排序,您可以使用 Arrays.sort():

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

然后films[0]将包含长度最短的电影,而最后一个元素将是长度最长的电影。

如果您需要通过其他字段进行比较,例如电影标题,您可以创建自定义比较器:

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

并传递给Arrays.sort()

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

然后 films[0] 将包含标题最短的电影,而最后一个元素将是标题最长的电影。

另一种解决方案是实施 Comparable<Film>:

@Override
public int compareTo(Film that) {
   return this.length - that.length;
}

并使用 org.apache.commons.lang3.ObjectUtils#minorg.apache.commons.lang3.ObjectUtils#max 如:

Film min = ObjectUtils.min(film1, film2);
Film max = ObjectUtils.max(film1, film2);