我想通过提供自定义顺序对包含不相关对象的列表进行排序。例如,我要排序的列表包含 Animal 类的对象。动物对象有一个称为类型的对象,可以是猫、老鼠或狗。我有一个自定义订单 Mouse < Cat < Dog。如何实现包含动物的列表按照我的自定义顺序排序?
特别是,给出以下代码,我不知道如何实现比较器。另外,这是一个简化的示例,我无法修改 Dog、Cat、Mouse 或 Animal 类。
// Cat and Mouse are similar
public class Dog {
...
}
public class Animal {
Object type;
public Animal(Object aType) {
type = aType;
}
// getter , setter etc.
}
public class Comparison {
List<Animal> animals;
public Comparison() {
Dog dog1 = new Dog();
Animal animal1 = new Animal(dog);
animals.add(animal1);
Cat cat1 = new Cat();
Animal animal2 = new Animal(cat);
animals.add(animal2);
// add other elements of type dog, cat or mouse
....
// sort the list with custom order: mouse<cat<dog
Collections.sort(animals,intComparator());
}
private Comparator<Animal> intComparator() {
return new Comparator<Animal>() {
@Override
public int compare(Animal first, Animal second) {
return ???;
}
};
}
}
一种解决方案是手动检查类型的类(通过instanceof)并对比较器中的顺序进行硬编码。然而,我有太多的类可以包含在 Animal 中(不仅仅是本示例中的三个类),因此这将产生大量的 if 情况。
private Comparator<Animal> intComparator() {
return new Comparator<FXNode>() {
@Override
public int compare(Animal first, Animal second) {
// if first is a mouse, return -1 because it is the 'smallest' object
if (first.getType() instanceof Mouse) return -1;
// if first is a cat and second a mouse, return 1 etc., a lot of if cases
}
最佳答案
怎么样:
enum Species { Cat, Dog, Mouse, ... };
class Animal {
Species species;
};
然后对于比较器:
private Comparator<Animal> intComparator() {
return new Comparator<FXNode>() {
@Override
public int compare(Animal first, Animal second) {
return first.species.compareTo(second.species);
}
}
}
订单来自枚举
。您可以通过使声明更加复杂来将属性(腿数、颜色等)附加到 Species
值。请参阅the Oracle tutorial .
关于Java - 将不相关的对象与自定义顺序进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25070294/