Reputation: 97
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.
Upvotes: 6
Views: 23434
Reputation: 1
just cast to E before -- this may solve the problem
boolean add(E (E)e);
Upvotes: -1
Reputation: 452
You should do the following:
((Collection<Object>)c).add(value);
Then the code will compile and run.
Upvotes: -2
Reputation: 1321
You can replace ? with Object. i think it will work
import java.util.ArrayList;
import java.util.Collection;
public class KaviTemre {
final Object value="kavi";
public static void main(String[] args) {
new KaviTemre().myMethod();
}
void myMethod()
{
Collection<Object> obj = new ArrayList<Object>();
final Collection<Object> c = (Collection<Object>)obj;
c.add(value);
for(Object o:c)
System.out.println(o.toString());
}
}
Upvotes: 0
Reputation: 337
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>
.
Upvotes: 5