Spongeebobble Spongeebobble - 1 year ago 173
Java Question

Java unchecked method invocation with ArrayList

When I run my code I get this warning:

warning: [unchecked] unchecked method invocation: method addAll in interface List is applied to given types
required: Collection<? extends E>
found: List
where E is a type-variable:
E extends Object declared in interface List



List<Sprite> snakeDotlist = new ArrayList<>();

Sprite tokenSprite = new Sprite((genRandomNumber(0, 64)), (genRandomNumber(0, 48)), 16, 16, "res/snakedot.png");


if (hasCollided(tokenSprite, snakeDotlist.get(0)))
snakeDotlist.get(0).score += 1;
snakeDotlist.addAll(genNewDots((int)snakeDotlist.get(0).prev1x, (int)snakeDotlist.get(0).prev1y, (int)snakeDotlist.get(0).prev2x, (int)snakeDotlist.get(0).prev1y));


public static List genFirstDots()
List<Sprite> list = new ArrayList<>();
list.add(new Sprite(3, 0, 16, 16, "res/snakedot.png"));
list.add(new Sprite(2, 0, 16, 16, "res/snakedot.png"));
list.add(new Sprite(1, 0, 16, 16, "res/snakedot.png"));
list.add(new Sprite(0, 0, 16, 16, "res/snakedot.png"));
return list;

I looked at a few other posts that said to change the declaration of snakeDotList from

List<Sprite> snakeDotlist = new ArrayList<Sprite>();


List<Sprite> snakeDotlist = new ArrayList<>();

but I still get the warning messages and I don't know how to solve it, any help?

Answer Source

You should change this:

public static List genFirstDots()

to this:

public static List<Sprite> genFirstDots()

The reason why the warning appears is because you are returning a List in genFirstDots() but you're adding the returned value to a List<Sprite>.

When no generic type arguments are given, generic types implicitly has an Object type argument, so List is actually List<Object>. When you try to append a list of objects to a list of sprites, the objects that the object list stores might not be compatible with Sprite and can't be added to the sprite list. Hence the warning.