Gre*_*lvo 4 java sorting object
极端新手在这里努力处理列表可能排序的所有不同方式.假设我有一个对象列表,每个对象都有几个可用于在不同情况下进行排序的键.我从这个线程得到了一些非常有用的信息: Java Interface Comparator静态比较,使用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
}
}
Run Code Online (Sandbox Code Playgroud)
但是,这似乎并不合适.我想我想在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();
}
};
Run Code Online (Sandbox Code Playgroud)
然后用法如下:
// 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
Run Code Online (Sandbox Code Playgroud)