This question already has answers here:
What is a raw type and why shouldn't we use it?
                                
                                    (15个答案)
                                
                        
                                2年前关闭。
            
                    
我正在使用带有包含函数的通用类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;
        }
    }
}


我不确定为什么在使用通用列表时会出现此错误?

最佳答案

您为T声明了通用类型参数TestThrows,但从未使用过。

这使得TestThrows testThrows = new TestThrows()的类型成为原始类型,
这会导致getExceptions()的返回类型也成为原始的List而不是List<Throwable>, so iterating over testThrows.getExceptions()returns Object 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<>();

10-06 07:19