我在使用泛型时发现了一种奇怪的行为.
在本课程中Foo<T>,该strings成员与T以下内容无关:
package test;
import java.util.ArrayList;
public class Foo<T> {
ArrayList<String> strings;
T getSome() {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
该类用于main:
package test;
public class Main {
public static void main() {
Foo<Integer> intFoo = new Foo<>();
Integer i = intFoo.getSome();
String s1 = intFoo.strings.get(0);
Foo rawFoo = new Foo();
Object o = rawFoo.getSome();
String s2 = rawFoo.strings.get(0); // Compilation error on this line
}
}
Run Code Online (Sandbox Code Playgroud)
编译错误是"不兼容的类型.必需:String found:Object".
似乎Java 在使用raw类型时忘记了Stringtype参数.ArrayListFoo
我的java版本是1.7.0_21
| 归档时间: |
|
| 查看次数: |
912 次 |
| 最近记录: |