Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixing error in java: incompatible types: java.lang.Object cannot be converted to capture#1 of?

Tags:

java

generics

My code declares a value variable of type Object:

final Object value;

This variable is then loaded with an object.

A generic collection variable is then declared and loaded:

final Collection<?> c = (Collection<?>) argumentDefinition.getFieldValue();

The collection variable is generic in both instances above, with brackets and a question mark that don't pass through in this text.

When I try to use the add method of the collection:

c.add(value)

I get the error message:

java: incompatible types:java.lang.Object cannot be converted to capture #1 of ?

The add method is declared in Collection as:

boolean add(E e);

How can I fix the error? I think I understand what's going on - the compiler creates a placeholder for the generic type that Object isn't compatible with. I can't use a raw type for the collection because I'm trying to eliminate raw types in the code. Do I need to use a helper function, and if so how exactly? Thank you.

like image 319
Nicholas Newell Avatar asked Apr 25 '15 19:04

Nicholas Newell


1 Answers

It's hard to tell what exactly your problem is without knowing what argumentDefinition.getFieldValue() returns, but a possible solution would be change your variable type from Collection<?> to Collection<Object>.

like image 102
Eli Avatar answered Oct 02 '22 13:10

Eli