2017-06-07 45 views
1

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

类型不匹配:不能从元素类型的对象转换为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; 
     } 
    } 
} 

我不知道这是为什么错误的我正在使用通用列表?

+0

您使用TestThrows的原始类型。这扰乱了你的方法调用的泛型。 –

回答

2

您为TestThrows声明了一个通用类型参数T,您从不使用它。

这使得其引起getExceptions()返回类型的TestThrows testThrows = new TestThrows()原始类型, 类型也可以是原始List代替List<Throwable>, so iterating over testThrows.getExceptions()returns对象references instead of Throwable`引用,你的循环没有通过汇编。

,因为你不使用T反正只要改变

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,你应该改变

TestThrows testThrows = new TestThrows(); 

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

的原因是因为你使用的原料种类...做的,而不是

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

的修复非常简单。相反的:

TestThrows testThrows = new TestThrows(); 

使用:

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