我有以下代碼:使用Java泛型錯誤
String test = "[{\"color\":\"red\"}]";
Class<? extends Base> baseObject = Base.class;
Collection<? extends Base> elements = new ArrayList<Base>();
if (test.startsWith("[")) {
elements.addAll(new ObjectMapper().readValue(test, Collection.class));
} else {
elements.add(new ObjectMapper().readValue(test, baseObject));
}
但是我對
elements.addAll(new ObjectMapper().readValue(test, Collection.class));
得到一個編譯警告:
The expression of type Collection needs unchecked conversion to conform to Collection<? extends capture#1-of ? extends Base>
和elements.add(new ObjectMapper().readValue(test, baseObject));
編譯錯誤:
The method add(capture#2-of ? extends Base) in the type Collection<capture#2-of ? extends Base> is not applicable for the arguments (capture#3-of ? extends Base)
出什麼問題了?
*什麼*錯誤? –
爲什麼不簡單'收集 元素=新的ArrayList ();'? –
assylias
'String test =「[{」color「:」red}]「;'< - 我認爲你忘了逃脫引號 –