This is a bit embarrassing. I have a compareTo function that I intend to use on a JButton, so when the user presses it they can see which is the highest ranked object. I already have a Listener class for the JButton but I don't know how to make the Listener use the compareTo function because it needs two parameters.
This is my compareTo function:
public int compareTo(Film film1, Film film2) {
if (film1.getFinalScore() < film2.getFinalScore()) return -1;
if (film1.getFinalScore() > film2.getFinalScore()) return 1;
return 0;
}
And this is the actionPerformed function in the Listener class:
@Override
public void actionPerformed(ActionEvent e) {
this.cm.compareTo(null, null);
}
The Auto-correct suggested to put the parameters to null to make it work, but it's obviously never as simple as the Auto-Correct suggests.
So, how can I make the Listener perform the compareTo function using all of my objects to list them from highest to lowest?
Thanks in advance!
As you need to compare 2 Films together you can do that in Film Class
by implementing Comparable<Film>
then implementing the compareTo
method in the class.
After That , Hold your films in any collection
as ArrayList
then simply call Collections.max(films)
to get the max film object in the list.
Here is the a Film class for demonstration:
public class Film implements Comparable<Film>{
int finalScore ;
public Film(int finalScore){
this.finalScore = finalScore;
}
public int getFinalScore(){
return this.finalScore;
}
@Override
public int compareTo(Film film2) {
if (this.getFinalScore() < film2.getFinalScore()) return -1;
if (this.getFinalScore() > film2.getFinalScore()) return 1;
return 0;
}
}
And this is the main :
public static void main(String[] args) {
ArrayList<Film> films = new ArrayList<>();
films.add(new Film(100));
films.add(new Film(400));
films.add(new Film(200));
films.add(new Film(300));
System.out.println(Collections.max(films).getFinalScore());//prints 400
}
So your actionPerformed will be like this
@Override
public void actionPerformed(ActionEvent e) {
Film maxFilm = Collections.max(films);
//then use maxFilm object to do anything you need
}