简体   繁体   English

Java泛型-意外范围

[英]Java Generics - Unexpected bounds

No Problems here 这里没问题

public class MyList<E extends Number> extends ArrayList<E> {
}

.

Unexcepted bound. 不受限制。 What does this mean? 这是什么意思? And why is it wrong? 为什么会这样呢? Thanks for help. 感谢帮助。

public class MyList<E extends Number> extends ArrayList<E extends Number> {

}

class MyList<E extends Number> is OK because you declare a type parameter, so you have to give it a name ( E ) and you can optionally declare it as bounded ( extends Number ). class MyList<E extends Number>是可以的,因为您声明了一个类型参数,因此必须给它命名( E ),并且可以选择将其声明为有界( extends Number )。

In extends ArrayList<E> instead you just have to "use" a type parameter: with " <E> " you refer to the parameter declared in your class, for which a bound is already given in its declaration. 相反,在extends ArrayList<E>您只需要“使用”类型参数:使用“ <E> ”,您可以引用类中声明的参数,在其声明中为其指定了界限。 " <? extends Number> " (with ? in place of E ) would also be accepted by the compiler (although it would be not what you want). 编译器也可以接受“ <? extends Number> ”(用?代替E )(尽管这不是您想要的)。 Instead, " <E extends Number> " is taken as a type parameter declaration, so it is a compile error. 取而代之的是,将“ <E extends Number> ”用作类型参数声明,因此它是编译错误。

public class MyList<E extends Number> extends ArrayList<E> {
    private static final long serialVersionUID = -1025575227555594680L;

}

This should work with no compilation error and no warnings even. 这应该没有编译错误,甚至没有警告。 Let me know if you still have the same error. 让我知道您是否仍然存在相同的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM