java - 在泛型集合中实现 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>
以便有可能检查Object
除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<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 o
只T 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
有人可以
- 确认我可以使用
@SuppressWarnings("unchecked")
,安全地忽略警告 - 建议我如何安全地投射
Object
到T
, - 解释为什么以上两点都不能满足,这样我就可以停止思考如何完成这项工作?
非常感谢!
解决方案
如果您想进行不受限制的搜索,则需要进行强制转换。您可以添加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.TreeMap
Object
推荐阅读
- applescript - 脚本编辑器
如何在传递到要单击的数字单元格之前将“数据”包装在超链接中 - python - 包含常量的模块的类型提示
- python - 如何选择和裁剪 SLIC 图像 Python 的多个超像素
- sql - 使用游标的动态 SQL
- python - Pandas read_sql() 有效,但 to_sql() 给出错误
- apache-flink - Flink SQL 匹配识别输出所有列
- angular - 角度将参数传递给服务
- libgit2sharp - libgit2sharp - 如何仅撤消工作副本中的更改?
- apache-spark - Pyspark 在写入磁盘时丢失数据
- r - 为动态条形图的每个条形分配标准颜色