1

I am using a generic class TestThrows< T > with a containing function that returns a generic list . My problem is i am unable to compile this program and it is throwing following error :

Type mismatch: cannot convert from element type Object to 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;
        }
    }
}

I am not sure why is this error as i am using generic list ?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
T-Bag
  • 10,916
  • 3
  • 54
  • 118

3 Answers3

2

You declared a generic type parameter T for TestThrows, which you never use.

That makes the type of TestThrows testThrows = new TestThrows() a raw type, which causes the return type of getExceptions() to also be a raw List instead of List<Throwable>, so iterating overtestThrows.getExceptions()returnsObjectreferences instead ofThrowable` references, and your loop doesn't pass compilation.

Just change

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

to

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

since you are not using T anyway.

If you do need T, you should change

TestThrows testThrows = new TestThrows();

to

TestThrows<SomeType> testThrows = new TestThrows<>();
Eran
  • 387,369
  • 54
  • 702
  • 768
1

the reason is because you are using raw types... do instead

TestThrows<Throwable> testThrows = new TestThrows<>();
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

The fix is very simple. Instead of:

 TestThrows testThrows = new TestThrows();

use:

TestThrows<Throwable> testThrows = new TestThrows<Throwable>();
tmucha
  • 689
  • 1
  • 4
  • 19