它總是抱怨有:編譯器是不滿我在Java中
The method add(Matrix<T>) in the type List<Matrix<T>> is not applicable for the arguments (Matrix<String>)
在提取類線:
matrixList.add(new Matrix<String>(attributes));
似乎有定義在我的仿製藥的問題這三類。有沒有簡單的方法來解決這個問題?嘗試了不同的方式,無法弄清楚。
public class Test {
public static void main(String[] args) {
Extractor<String> extractor = new Extractor<>();
extractor.extract();
}
}
class Extractor<T> {
private List<Matrix<T>> matrixList;
public Extractor() {
this.matrixList = new ArrayList<>();
}
public void extract() {
List<Attribute<String>> attributes = new ArrayList<>();
attributes.add(new Attribute<String>("Test 1"));
attributes.add(new Attribute<String>("Test 2"));
// !!!! The compiler is complaining here!
matrixList.add(new Matrix<String>(attributes));
}
public List<Matrix<T>> getList() {
return matrixList;
}
}
class Matrix<T> {
private List<Attribute<T>> attributes;
public Matrix(List<Attribute<T>> attributes) {
this.attributes = attributes;
}
public List<Attribute<T>> getAttributes() {
return attributes;
}
}
class Attribute<T> {
private T attribute;
public Attribute(T attr) {
attribute = attr;
}
public T getAttr() {
return attribute;
}
}
我不這麼認爲,在找到這樣的障礙簡單的插圖。 T可能是String或其他類型。在這個課程中,他可以在這裏爲Matrix使用Matrix ,他可以在任何地方使用Matrix 作爲任何類型。 –
htpvl
@ kimdung這是完全錯誤的。你真的瞭解泛型要解決什麼問題嗎? –
@kimdung在這種情況下,提取方法應該返回'Matrix'而不是將其添加到類型爲'T'的專用字段。 –
fRoStBiT