我遇到了这段代码
class Test<String> {
String my = "Hello!"; //--- 1
String s = new String("aaa"); //---- 2
}
代码提供2个编译时错误: for 1.向String添加一个强制转换 for 2.无法实例化字符串
为什么这样?
List <? extends String(or any random class)> = new ArrayList<Anyclass>();
此代码编译的原因是什么?
答案 0 :(得分:2)
使用Test<String>
您声明自己的自定义类型,隐藏java.lang.String
使用
class Test<T> {
答案 1 :(得分:0)
为泛型类定义泛型类型参数时,请不要使用现有的类名(例如String)。
如果你使用更传统的参数名称T,你得到的错误会更清楚:
T my = "Hello!"; // doesn't compile since T can be anything, not necessarily a String
T s = new T("aaa"); // doesn't compile since Java does not allow you to call a constructor of
// a generic type parameter (new T() wouldn't work either), and you don't
// even know whether the class used as the actual parameter when you instantiate
// your generic class would even have a constructor that accepts a String
答案 2 :(得分:0)
您声明了一个名为String
的泛型类型参数,它与内置String
类的常规引用不同。因此,my
和s
的类型是您的类型参数,而不是内置String
,因此它们不兼容。
从String
类中删除Test
泛型类型参数;它毫无用处。
class Test {
此行无法编译,因为Anyclass
未展开String
(但它不能; String
为final
。
List <? extends String> x = new ArrayList<Anyclass>();
答案 3 :(得分:0)
您的通用类型class Test<String>
并不代表java.lang.String
。这里发生的是你将泛型类型的名称设置为String
,而不是它的值。
换句话说,您的代码可以重写为
class Test<T> {
T my = "Hello!"; //--- 1
T s = new T("aaa"); //---- 2
}
因此,编译器无法安全地假设T
实际上是String
,因此它会阻止您使用T
类型初始化instances of Stirng
类型的变量。
此代码编译的原因是什么?
List <? extends String(or any random class)> = new ArrayList<Anyclass>();
好吧,在这里,您不是要决定如何命名泛型类型,而是应该表示什么值。 <? extends String>
表示java.lang.String
或从中派生的类型(在这种情况下不会发生因为String是最终类)。