The extreme newbie here is struggling to get a handle to all the different ways to sort the list. Suppose I have a list of objects, and each object has several keys that can be used for sorting in different circumstances. I got very useful information from this topic:
Comparing Static Comparisons of the Java Interface Comparator using the first Qwerkys example as a generated model:
class Dog {
private String name;
private int age;
private int height;
private int weight;
Dog(String n, int a, int b, int c){
name = n;
age = a;
height = b;
weight = c;
}
public String getDogName(){
return name;
}
public int getDogAge(){
return age;
}
public int getDogHeight(){
return height;
}
public int getDogWeight(){
return weight;
}
}
class DogComparator1 implements Comparator<Dog> {
@Override
public int compare(Dog d, Dog d1){
return d.getDogAge() - d1.getDogAge();
}
}
class DogComparator2 implements Comparator<Dog> {
@Override
public int compare(Dog d, Dog d1){
return d.getDogHeight() - d1.getDogHeight();
}
}
class DogComparator3 implements Comparator<Dog> {
@Override
public int compare(Dog d, Dog d1){
return d.getDogWeight() - d1.getDogWeight();
}
}
public class Example{
public static void main(String args[]){
List<Dog> dogList = new ArrayList<>();
.
.
DogComparator1 compare1 = new DogComparator1();
DogComparator2 compare2 = new DogComparator2();
DogComparator3 compare3 = new DogComparator3();
Collections.sort(list, compare1);
Collections.sort(list, compare2);
Collections.sort(list, compare3);
}
}
But that just doesn't seem right. I think I want to infer the definitions of the comparator "inside" the Dog class in order to encapsulate them. But, I canβt understand how to do this.
Am I on the right track? If so, then it will be very useful for you to help with the correct syntax.