[英]Comparing generic type T to Object
我有以下 class
public class SkipListSet<T extends Comparable<T>> implements SortedSet<T> {
我正在使用内部包装器 class:
class Node<T extends Comparable<T>> {
由于我正在实现SortedSet
接口,因此我开始处理所需的类。
虽然, contains 有 Object 作为参数,但我想知道为什么我不能将其更改为 T 目标。 如果我这样做,我会收到以下错误:
The method contains(T) of type SkipListSet<T> must override or implement a supertype method
@Override
public boolean contains(Object target) {
ArrayList <Node<T>> lastNodeSeen = new ArrayList<Node<T>>();
Node<T> current;
// Start at top of header
current = header.getLevel(maxHeight);
while (current.nextNode.data != target) {
// No reference to other node
if (current.nextNode == null) {
// retreat is not an option, we must dig deeper
if (current.prevNode == null)
{
current = current.getLevel(current.getHeight() - 1);
}
// we must retreat
current = current.prevNode;
}
// If
else if (current.nextNode.data.compareTo(target) > 0) { // if data > target, then 1
}
}
return false;
}
为什么会这样?
我想办法解决这个问题是通过类型转换 Object 目标。
像这样:
T newTarget = (T)(目标);
您将收到以下警告:
Type safety: Unchecked cast from Object to T
但出于我的目的,我不介意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.