有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java需要创建一个带有自定义比较器的二进制搜索树,但似乎无法让它工作

我正在尝试使用树集创建一个二叉搜索树。我知道根据定义,集合不包含任何重复的条目。然而,我确信如果我创建自己的比较器,我可以允许树集接受重复的条目。我已经这样做了:

public class A3BSTree <E> implements Tree <E> {

    private TreeSet<E> tree;
    private LinkedList<E> arr1;
    private MyComparator comp;

    public A3BSTree(){
        tree = new TreeSet<>(comp);
    }

    ...
    ...
    ...

    private class MyComparator implements Comparator<E> {
        @SuppressWarnings("unchecked")
        @Override
        public int compare(E e1, E e2) {
            if (((A3BSTree<E>.MyComparator) e1).compareTo(e2) < 0) {
                return -1;
            }
            else if (e1.equals(e2)) {
                return 0;
            }
            else {
                return 1;
            }
        }

        public int compareTo(E e) {
            return this.compareTo(e);
        }
    }

}

我不想要答案,我只需要解释一下为什么树集仍然不接受副本。我只需要被引导到正确的方向。问题是我不能用泛型创建比较器吗


共 (1) 个答案

  1. # 1 楼答案

    java。util。TreeSet add()方法

    java。util。TreeSet类使用add方法将元素添加到集合中。此方法不允许重复。它使用Javadoc中提到的equals()方法检测重复项

    public boolean add(E e) Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if the set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.

    当前比较器的实现

    根据您的比较器实现,您希望equals方法识别重复项(可能您已经覆盖了它?)

    } else if (e1.equals(e2)) {
        return 0;
    }
    

    如果是这样的话,我相信TreeSet基于equals()方法拒绝重复项的行为是正确的

    另一方面,这里使用Comparable方法可能比使用Comparator更好,因为它允许对象与其自身的实例进行比较(区别是explained here