为这个复杂的问题道歉,但我想不出更简单的提问方法。我目前正在试验泛型,遇到了一些我无法理解的事情。我有一个带有类型参数T
的泛型类,它有一个带有类型参数E
的泛型内部类。但是,内部类的构造函数需要一个T
。
如果我用Outer<String>
实例化外部类,用<Integer>
实例化内部类,并使用整数调用其构造函数,则没有问题。这对我来说没有任何意义,因为在这种情况下,构造函数应该只使用Outer
type 参数中设置的String
。为什么会这样呢?
但是,如果我在内部类中创建一个需要T
的方法,The method method(T) in the type Outer<T>.InnerGeneric<Integer> is not applicable for the arguments (int)
对我来说确实有意义。为什么构造函数方法不会发生这种情况?
这是我的代码片段:
public class Outer<T> {
class InnerGeneric<E> {
InnerGeneric(T t) {
//do something
}
void method(T t) {
//do something
}
}
class Inner {
}
Outer(T t) {
InnerGeneric<T> inner1 = new InnerGeneric<>(t);
InnerGeneric<Integer> inner2 = new InnerGeneric<>(1); //i do not get any error here,
and the code can run just
fine with this, why???
inner2.method(t);
inner2.method(1); //get a compilation error here, this makes sense to me
}
public static void main(String[] args) {
Outer<String> outer = new Outer<>("Any string");
}
}
编辑:我正在使用Eclipse,不确定这对javac的版本意味着什么,因为我对这一切仍然相当陌生
我用javac 1.8.0_25尝试过,它给出了编译错误,正如你所期望的那样,而Eclipse确实没有。 (我从你引用的错误消息中假设你正在使用的是Eclipse。
这似乎是 Eclipse 编译器中的一个错误,特别是在处理菱形运算符时。如果将该行替换为InnerGeneric<Integer> inner2 = new InnerGeneric<Integer>(1);
则 Eclipse 也会拒绝它。
(虽然我的搜索技能不是很好,但据我所知,它还没有被记录为 Eclipse 错误,所以你应该报告它。