首页 > 解决方案 > 在泛型集合中实现 remove(Object o)

问题描述

我正在编写一个基于二叉树模型的通用集合。

class MyTree <T extends Comparable<T>> extends AbstractCollection<T>{...}

底层Node<T>类(除其他外)包含以下方法:

public Node<T> getLeft()  // left Node
public Node<T> getRight() // right Node
public T getValue()       // value stored in the Node

我想重写boolean contains(Object o)接口的方法,AbstractCollection<T>以便有可能检查ObjectT.

对于 O(log n) 中的树遍历,泛型类型T必须实现Comparable<T>,因此它具有方法compareTo(T t)

我的代码:

@Override
public boolean contains(Object o){
    T t = (T) o; // produces warning (see below)
    BSNode<T> currentNode = this.root;
    while(currentNode != null){
        if(currentNode.getValue().equals(o)) {return true;}
        if(currentNode.getValue().compareTo(t) < 0)  {currentNode = currentNode.getRight();}
        if(currentNode.getValue().compareTo(t) > 0)  {currentNode = currentNode.getLeft();}
    }
    return false;
}

问题是我不能Object oT t使用compareTo(T t). 从技术上讲,Object's 可以转换为T,但作为T泛型类型,我收到以下警告:

warning: [unchecked] unchecked cast
          T t = (T) o;
                    ^
required: T
found:    Object
where T is a type-variable:
  T extends Comparable<T> declared in class MyTree

有人可以

  1. 确认我可以使用@SuppressWarnings("unchecked"),安全地忽略警告
  2. 建议我如何安全地投射ObjectT,
  3. 解释为什么以上两点都不能满足,这样我就可以停止思考如何完成这项工作?

非常感谢!

标签: javagenericscollectionscomparable

解决方案


如果您想进行不受限制的搜索,则需要进行强制转换。您可以添加instanceof以防止演员出现异常,但这也不理想。

考虑T如下改变边界:

class MyTree <T extends Comparable<? super T>> extends AbstractCollection<T>{...}

由于您进行了覆盖,因此非常需要抑制警告。演员表应如下所示:

@SuppressWarnings("unchecked")
Comparable<? super T> t = (Comparable<? super T>) o;

有关如何在Java 源代码中完成的示例,请参见getEntry方法的源代码(他们这样做的原因相同 - 需要使用签名覆盖覆盖方法)。java.util.TreeMapObject


推荐阅读