如何使用不同的比较器创建两个通用结构实例?

时间:2014-10-14 07:18:05

标签: java generics data-structures comparison

我正在使用Java中的泛型进行抽象的AVL树实现。我需要具有相同数据实例但具有不同键的树的多个实例。 例如:我们考虑数据类Car。我需要它的实例同时在两棵树中。但是第一棵树将按照牌照排序,第二棵树按照VIN号排序。 如何确保?

2 个答案:

答案 0 :(得分:2)

创建树时需要提供比较器。 simpke实现可以在根节点中保持对它的引用。使用工厂方法,这样的事情可以起作用:

public class MyTreeNode<T> {
    private Comparator<? super T> comparator;

    protected MyTreeNode() {}

    public static <T> MyTreeNode<T> create(Comparator<? super T> comparator) {
        MyTreeNode<T> node = new MyTreeNode<T>();
        node.comparator = comparator;
        return node;
    }
}

根据您的使用方式,您可以将引用传递给子节点。

答案 1 :(得分:2)

由于您的抽象树实现是基于泛型构建的,因此您可以将比较器传递给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


}