简体   繁体   中英

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

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.

在不知道argumentDefinition.getFieldValue()返回什么的情况下,很难确定您的问题究竟是什么,但可能的解决方案是将您的变量类型从Collection<?>更改为Collection<Object>

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());
    }
}

之前只是投射到 E - 这可能会解决问题

boolean add(E (E)e);

You should do the following:

((Collection<Object>)c).add(value);

Then the code will compile and run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM