我正在编写一个基于二叉树模型的泛型集合.
class MyTree > extends AbstractCollection{...}
基础节点< T> class(以及其他)包含以下方法:
public Node getLeft() // left Node
public Node getRight() // right Node
public T getValue() // value stored in the Node
我想覆盖接口AbstractCollection< T>接口的方法boolean contains(Object o).有可能检查除T以外的类型的对象.
对于O(log n)中的树遍历,泛型类型T必须实现Comparable< T>,因此它具有compareTo(T t)方法.
我的代码:
@Override
public boolean contains(Object o){
T t = (T) o; // produces warning (see below)
BSNode 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;
}
问题是我不能只使用compareTo(T t)将Object o强制转换为T t.从技术上讲,Object可以转换为T,但由于T是泛型类型,我收到此警告:
warning: [unchecked] unchecked cast
T t = (T) o;
^
required: T
found: Object
where T is a type-variable:
T extends Comparable declared in class MyTree
也可以
>确认我可以使用@SuppressWarnings(“unchecked”)安全地忽略警告,
>建议我如何安全地将Object转换为T,
>解释为什么上述两点都不能满足,所以我可以不再考虑如何使这项工作?
非常感谢!