Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 每个循环的通用列表和_Java_Generics_Raw Types - Fatal编程技术网

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>();