使用Comparable查找最大/最小值

时间:2015-03-17 16:44:57

标签: java comparable

我有一个对象类

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

3 个答案:

答案 0 :(得分: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]将包含最短标题的电影,而最后一个元素将是标题最长的电影。

答案 1 :(得分: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];
        }
    }
}

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

答案 2 :(得分: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);