在准备SCJP-6考试时,我遇到了一个难题。我一个人找不到答案。请回答问题并给出简短的评论:
abstract class A<K extends Number> {
// insert code here
} public abstract <K> A<? extends Number> useMe(A<? super K> k);public abstract <K> A<? super Number> useMe(A<? extends K> k);public abstract <K> A<K> useMe(A<K> k);public abstract <V extends K> A<V> useMe(A<V> k);public abstract <V super K> A<V> useMe(A<V> k);public abstract <V extends Character> A<? super V> useMe(A<K> k);public abstract <V super Character> A<? super V> useMe(A<K> k);可以在上面的占位符中插入哪种方法?
我试过看说明书。那些对我没什么帮助。
发布于 2010-07-28 10:22:42
回答1,2,3:泛型类型K阴影类类型为K。在这些方法中,K只是新的泛型类型。编译器试图传递条件计算<K extends Number>。方法1,2传球和3-失败。
答案4完全正确。
答案5,7有语法错误。
答案6不正确,因为测试<V extends Number>将失败。
发布于 2010-05-26 15:16:03
要做到这一点,最好的方法是尝试每个方法,并查看编译器告诉您的内容。我对每个结果都得到了以下结果(使用NetBeans,因此您的结果可能略有变化):
public abstract <K> A<? extends Number> useMe(A<? super K> k);
// seems to work
public abstract <K> A<? super Number> useMe(A<? extends K> k);
// type parameter ? extends K is not within its bound
public abstract <K> A<K> useMe(A<K> k);
// type parameter K is not within its bound
public abstract <V extends K> A<V> useMe(A<V> k);
// seems to work
public abstract <V super K> A<V> useMe(A<V> k);
// > expected
// illegal start of type
// <identifier> expected
// missing method body, or declare abstract
// cannot find symbol
// symbol: class V
// location: class A<K>
public abstract <V extends Character> A<? super V> useMe(A<K> k);
// type parameter ? super V is not within its bound
public abstract <V super Character> A<? super V> useMe(A<K> k);
// > expected
// illegal start of type
// <identifier> expected
// missing method body, or declare abstract发布于 2010-05-26 15:50:42
我试着解释一下.
1不起作用,因为你不能用A<? super K>代替A<K extends Number>.不能保证超类扩展与子类相同的类。
1、2和3不能工作,因为初始类型参数隐藏了类声明中使用的原始K。
5不起作用,因为<V super K>不能代替<K extends Number>.不能保证超类扩展与子类相同的类。
6和7应该是显而易见的。
4起作用是因为,如果我们知道V扩展K,那么我们就知道V扩展数(因为K扩展V的所有类都是扩展的)。因此,我们可以用A<V>代替<K extends Number>。
我希望这有道理..。也许有人能来解释得更好。
https://stackoverflow.com/questions/2914114
复制相似问题