英文:
Comparing generic type T to Object
问题
我有以下的类:
public class SkipListSet<T extends Comparable<T>> implements SortedSet<T> {
我正在使用一个内部包装类:
class Node<T extends Comparable<T>> {
由于我正在实现SortedSet
接口,我开始着手处理所需的类。
但是,contains
方法的参数是Object
,我想知道为什么我不能将其更改为T target
。如果我这样做,我会得到以下错误:
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;
// 从头部的顶层开始
current = header.getLevel(maxHeight);
while (current.nextNode.data != target) {
// 没有引用到其他节点
if (current.nextNode == null) {
// 退后不是一个选项,我们必须深入挖掘
if (current.prevNode == null)
{
current = current.getLevel(current.getHeight() - 1);
}
// 我们必须后退
current = current.prevNode;
}
// 如果
else if (current.nextNode.data.compareTo(target) > 0) { // 如果 data > target,那么返回1
}
}
return false;
}
为什么会出现这种情况呢?
英文:
I have the following class
public class SkipListSet<T extends Comparable<T>> implements SortedSet<T> {
I am using an internal wrapper class:
class Node<T extends Comparable<T>> {
Since I am implementing the SortedSet
interface, I am starting to tackle the required classes.
Though, contains has Object as an argument, I wonder why I can't change this to T target. If I do I get the following error:
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;
}
Why is this the case?
答案1
得分: 1
SortedSet
接口扩展了 Set
接口,该接口定义了以下形式的 contains
方法:
boolean contains(Object o);
该参数明确指定为一个 Object,这就是为什么在覆盖时无法将其更改为 T
。
英文:
The SortedSet
interface extends the Set
interface, which defines the method contains
like so:
boolean contains(Object o);
The parameter is explicitly specified to be an Object, which is why you can't change it to T
when overriding it.
答案2
得分: 0
我找到了解决这个问题的方法,就是通过将目标对象进行类型转换。像这样:
T newTarget = (T)(target);
你会得到以下警告:
类型安全性:从Object到T的未经检查的转换
但对于我的目的,我不介意它。
英文:
I figure out a way to solve this problem is by typecasting Object target.
Like so:
T newTarget = (T)(target);
You'll get the following warning:
Type safety: Unchecked cast from Object to T
But for my purposes I don't mind it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论