When comparing two different lists, then the approach laid out is the main way to go about it really. If you just wanted to sort the contestants in a single list easily by their height say, then you would use the
Comparable interface. However, this doesn't really do the behaviour you need for comparing two lists, unless you use it for sorting and then finding values quicker using a binary search etc.
If you're interested in this idea anyway, let me show you what the API states:
This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.
and
Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort).
What this means, is that you implement the only method of Comparable, which has a signatue of:
public int compareTo(Object other){}
where object will be the generic type you specific and int will be the indicator for the natural ordering. If the value of the object is less than the value of the `other` object, then -1 will be returned. If they're equal, 0 will be returned. In the case of member variable being greater than `other`, then you guessed it, 1 is returned.
If you implement the interface and the method alike, then using
Collections.sort(), you pass in your List and bobs your uncle; your objects will now be order based on the natural ordering you defined.
To help you better understand, I've concocted a quick and workable example which you can find below.
Best of luck, and be sure to come back if you have any further questions.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Contestant implements Comparable<Contestant>{
private final float height;
public Contestant(float height){
this.height = height;
}
public float getHeight(){
return this.height;
}
@Override
public int compareTo(Contestant other) {
if(this.height < other.getHeight()){
return -1;
}else if(this.height > other.getHeight()){
return 1;
}
return 0;
}
public static void main(String[] args){
List<Contestant> contestants = new ArrayList<Contestant>();
contestants.add(new Contestant(2.0f));
contestants.add(new Contestant(4.0f));
contestants.add(new Contestant(1.0f));
contestants.add(new Contestant(3.0f));
Collections.sort(contestants);
for(Contestant contestant : contestants){
System.out.println(contestant.getHeight());
}
}
}
This code gives the output of:
HTML Code:
1.0
2.0
3.0
4.0