这里的极端新手正在努力掌握列表可能排序的所有不同方式。假设我有一个对象列表,每个对象都有几个键,可用于在不同情况下进行排序。我从这个线程中得到了一些非常有用的信息: Java Interface Comparator static compare , 使用 Qwerky 的第一个示例作为创建的模型:
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[]){
// Creat list of dog objects
List<Dog> dogList = new ArrayList<>();
// Add a buch of dogs to the list here
.
.
// Create the Comparators
DogComparator1 compare1 = new DogComparator1();
DogComparator2 compare2 = new DogComparator2();
DogComparator3 compare3 = new DogComparator3();
// Sort the list using Comparators
Collections.sort(list, compare1); // Sort by age
Collections.sort(list, compare2); // Sort by height
Collections.sort(list, compare3); // Sort by weight
}
}
但是,这似乎不对。我想我想将比较器定义拉到 Dog 类“内部”以很好地封装它们。但是,不知道该怎么做。
我走在正确的轨道上吗?如果是这样,将不胜感激帮助正确的语法。
最佳答案
您绝对是在正确的轨道上。
我只是将其添加到您的 Dog
类中:
public static final Comparator<Dog> COMPARE_BY_AGE = new Comparator<Dog>() {
@Override
public int compare(Dog d, Dog d1) {
return d.getDogAge() - d1.getDogAge();
}
};
public static final Comparator<Dog> COMPARE_BY_HEIGHT = new Comparator<Dog>() {
@Override
public int compare(Dog d, Dog d1) {
return d.getDogHeight() - d1.getDogHeight();
}
};
public static final Comparator<Dog> COMPARE_BY_WEIGHT = new Comparator<Dog>() {
@Override
public int compare(Dog d, Dog d1) {
return d.getDogWeight() - d1.getDogWeight();
}
};
然后用法如下:
// Sort the list using Comparators
Collections.sort(list, Dog.COMPARE_BY_AGE); // Sort by age
Collections.sort(list, Dog.COMPARE_BY_HEIGHT); // Sort by height
Collections.sort(list, Dog.COMPARE_BY_WEIGHT); // Sort by weight
关于java - 使用不同的键对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28374518/