我正在使用 Java 中的泛型来实现抽象 AVL 树。我需要有多个具有相同数据实例但具有不同键的树实例。 例如:让我们考虑数据类 Car。我需要它的实例同时位于两棵树中。但第一棵树将按车牌排序,第二棵树将按 VIN 号排序。 如何保证?
最佳答案
由于您的抽象树实现是建立在泛型之上的,因此您可以将比较器传递给 avl 树构造函数,这样您就知道如何根据比较器来保持树中的顺序。
class Tree<T> {
private final Comparator<T> comparator;
public Tree(final Comparator<T> comparator) {
this.comparator = comparator;
}
}
class Car {
private String model;
private String VIN;
private String licencePlate;
public String getModel() {
return this.model;
}
public String getVIN() {
return this.VIN;
}
public String getLicencePlate() {
return this.licencePlate;
}
}
public static void main(final String[] args) {
Comparator<Car> comp1 = new Comparator<Car>() {
@Override
public int compare(final Car car1, final Car car2) {
return car1.getVIN().compareTo(car2.getVIN());
}
};
Comparator<Car> comp2 = new Comparator<Car>() {
@Override
public int compare(final Car car1, final Car car2) {
return car1.getLicencePlate().compareTo(car2.getLicencePlate());
}
};
Tree<Car> tree1 = new Tree<Car>(comp1); //this tree will keep order according to car's VIN
Tree<Car> tree2 = new Tree<Car>(comp2); // this tree will keep order according to car's licence plate
}
关于java - 如何使用不同的比较器创建通用结构的两个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26354810/