gpt4 book ai didi

java - 编译器对我在 Java 中的泛型不满意

转载 作者:行者123 更新时间:2023-11-29 06:52:09 25 4
gpt4 key购买 nike

它总是提示:

The method add(Matrix<T>) in the type List<Matrix<T>> is not applicable for the arguments (Matrix<String>)

在 Extractor 类的行中:

matrixList.add(new Matrix<String>(attributes));

在这 3 个类中定义我的泛型时似乎有问题。有没有简单的方法来解决这个问题?尝试了不同的方法,无法弄清楚。

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

最佳答案

您的代码根本没有意义。你正在制作 Extractor等通用,这意味着您希望它适用于不同类型。

然而,在Extractor.extract()方法,您正在专门创建一个 MatrixString并将其放入您的 List<Matrix<T>> matrixList .

如果您的代码仅适用于字符串,那么您不应该将其设为通用。只需制作 List<Matrix<String>> matrixList .

想一想:如果你现在正在创建一个 Extractor<Integer> intExtractor , 并调用 intExtractor.extract() ,你的代码如何工作才合理?

或者,为了进一步完善您的设计,可以:

interface Extractor<T> {
public List<Matrix<T>> extract();
}

class DummyStringMatrixExtractor implements Extractor<String> {

// useless now, can be put in extract()
private List<Matrix<T>> matrixList;

public Extractor() {
this.matrixList = new ArrayList<>();
}

@Override
public List<Matrix<String>> extract() {
List<Attribute<String>> attributes = new ArrayList<>();

attributes.add(new Attribute<String>("Test 1"));
attributes.add(new Attribute<String>("Test 2"));

matrixList.add(new Matrix<String>(attributes));

return matrixList;
}

// useless now
public List<Matrix<T>> getList() {
return matrixList;
}
}

关于java - 编译器对我在 Java 中的泛型不满意,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44447931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com