Java 每个循环的通用列表和
我正在使用一个泛型类Java 每个循环的通用列表和,java,generics,raw-types,Java,Generics,Raw Types,我正在使用一个泛型类TestThrows,它包含一个返回泛型列表的函数。我的问题是我无法编译此程序,它抛出以下错误: 类型不匹配:无法从元素类型对象转换为可丢弃的 public class Test { public static void main( String[] args ) { TestThrows testThrows = new TestThrows(); // compile error on the next line
TestThrows
,它包含一个返回泛型列表的函数。我的问题是我无法编译此程序,它抛出以下错误:
类型不匹配:无法从元素类型对象转换为可丢弃的
public class Test
{
public static void main( String[] args )
{
TestThrows testThrows = new TestThrows();
// compile error on the next line
for ( Throwable t : testThrows.getExceptions() )
{
t.toString();
}
}
static class TestThrows< T >
{
public List< Throwable > getExceptions()
{
List< Throwable > exceptions = new ArrayList< Throwable >();
return exceptions;
}
}
}
公共类测试
{
公共静态void main(字符串[]args)
{
TestThrows TestThrows=新的TestThrows();
//下一行出现编译错误
for(Throwable t:testThrows.getExceptions())
{
t、 toString();
}
}
静态类TestThrows
{
公共列表getExceptions()
{
Listexceptions=new ArrayList();
返回异常;
}
}
}
我不确定为什么会出现此错误,因为我正在使用泛型列表?您为
TestThrows
声明了一个泛型类型参数T
,您从未使用过该参数
这使得TestThrows TestThrows=new TestThrows()
的类型成为原始类型,
这会导致getExceptions()
的返回类型也是原始的List
而不是List,因此迭代testThrows.getExceptions()会返回Object引用而不是Throwable`references,并且循环不会通过编译
换衣服
static class TestThrows< T >
{
public List< Throwable > getExceptions()
{
List< Throwable > exceptions = new ArrayList< Throwable >();
return exceptions;
}
}
到
TestThrows TestThrows=newtestthrows();
原因是您使用的是原始类型。。。取而代之
TestThrows<Throwable> testThrows = new TestThrows<>();
TestThrows TestThrows=newtestthrows();
修复非常简单。而不是:
TestThrows testThrows = new TestThrows();
使用:
TestThrows TestThrows=newtestthrows();
您使用原始类型的测试抛出。这会弄乱方法调用的泛型。
TestThrows<SomeType> testThrows = new TestThrows<>();
TestThrows<Throwable> testThrows = new TestThrows<>();
TestThrows testThrows = new TestThrows();
TestThrows<Throwable> testThrows = new TestThrows<Throwable>();