使用Comparable查找最大/最小值

问题描述 投票:1回答:3

我有一个对象类

public class Film implements Comparable<Film>

我正在使用Eclipse,并想知道为什么Film用红色加下划线,错误说:

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

现在我的主要问题是:

如何获得最大/最小用户提交的电影长度和标题?

我的对象类Film具有电影标题和电影长度以及toString方法的getter和setter方法。在this文章(#3)之后,我在对象类中创建了另外两个方法:

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

我可以使用这些来查找和打印用户提交的胶片长度的最大/最小值吗?

如果是这样,怎么样?

如果没有,这样做的正确方法是什么?

测试类如下:

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());
        }
    }
}
java comparable
3个回答
2
投票

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

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

如果您只需要按胶片长度对对象进行排序,您可以使用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]将包含具有最短标题的电影,而最后一个元素将是具有最长标题的电影。


0
投票

为简单起见,我将你的Film类打包,以显示如何实现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];
        }
    }
}

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


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);
© www.soinside.com 2019 - 2024. All rights reserved.