通用列表和for-each循环

时间:2017-06-07 09:56:35

标签: java generics raw-types

我正在使用泛型类TestThrows< T >,其中包含一个返回通用列表的包含函数。我的问题是我无法编译这个程序,它抛出以下错误:

类型不匹配:无法从元素类型Object转换为Throwable

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;
        }
    }
}

我不知道为什么会出现这个错误,因为我使用的是通用列表?

3 个答案:

答案 0 :(得分:2)

您为T声明了一个永不使用的泛型类型参数TestThrows

这使得TestThrows testThrows = new TestThrows()的类型成为原始类型, 这导致返回类型getExceptions()也是原始List而不是List<Throwable>, so iterating over testThrows.getExceptions()returns对象references instead of Throwable`引用,以及您的循环不通过编译。

只需更改

static class TestThrows< T >
{
    public List< Throwable > getExceptions()
    {
        List< Throwable > exceptions = new ArrayList< Throwable >();
        return exceptions;
    }
}

static class TestThrows
{
    public List< Throwable > getExceptions()
    {
        List< Throwable > exceptions = new ArrayList< Throwable >();
        return exceptions;
    }
}

因为你还没有使用T

如果确实需要T,则应更改

TestThrows testThrows = new TestThrows();

TestThrows<SomeType> testThrows = new TestThrows<>();

答案 1 :(得分:1)

原因是因为你正在使用原始类型......而是

TestThrows<Throwable> testThrows = new TestThrows<>();

答案 2 :(得分:0)

修复非常简单。而不是:

 TestThrows testThrows = new TestThrows();

使用:

TestThrows<Throwable> testThrows = new TestThrows<Throwable>();
相关问题