修复 java 中的错误:不兼容的类型:java.lang.Object 无法转换为 capture#1 of?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29869678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fixing error in java: incompatible types: java.lang.Object cannot be converted to capture#1 of?
提问by Nicholas Newell
My code declares a value variable of type Object:
我的代码声明了一个 Object 类型的值变量:
final Object value;
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();
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:
当我尝试使用集合的 add 方法时:
c.add(value)
c.add(value)
I get the error message:
我收到错误消息:
java: incompatible types:java.lang.Object cannot be converted to capture #1 of ?
java:不兼容的类型:java.lang.Object 无法转换为捕获 #1 of ?
The add method is declared in Collection as:
add 方法在 Collection 中声明为:
boolean add(E e);
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.
我该如何修复错误?我想我明白发生了什么 - 编译器为 Object 不兼容的泛型类型创建了一个占位符。我不能为集合使用原始类型,因为我试图消除代码中的原始类型。我是否需要使用辅助函数,如果需要,具体如何使用?谢谢你。
回答by Eli
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>
.
在不知道argumentDefinition.getFieldValue()
返回什么的情况下很难确定您的问题究竟是什么,但可能的解决方案是将您的变量类型从 更改Collection<?>
为Collection<Object>
。
回答by kavi temre
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());
}
}
回答by Vasile Rotaru
You should do the following:
您应该执行以下操作:
((Collection<Object>)c).add(value);
Then the code will compile and run.
然后代码将编译并运行。