我有一个场景,我想将相同的逻辑应用于不同的类型。
interface TrimAlgo<T> {
public List<T> trim(List<T> input);
}
class SizeBasedTrim<T> implements TrimAlgo<T> {
private final int size;
public SizeBasedTrim(int size) {
this.size = size;
}
@Override
public List<T> trim(List<T> input) {
// check for error conditions, size < input.size etc.
return input.subList(0, size);
}
}
// Will have some other type of TrimAlgo
class Test {
private TrimAlgo<?> trimAlgo;
public Test(TrimAlgo<?> trimAlgo) {
this.trimAlgo = trimAlgo;
}
public void callForString() {
List<String> testString = new ArrayList<String>();
testString.add("1");
trimAlgo.trim(testString); // Error The method get(List<capture#3-of ?>) in the type TrimAlgo<capture#3-of ?> is not applicable for the arguments (List<String>)
}
public void callForInt() {
// create int list and call trim on it
}
}
有什么办法可以实现这一点吗?请告诉我。谢谢!
最佳答案
在我看来,你需要制作 trim()
通用方法而不是 TrimAlgo
类:
interface TrimAlgo {
<T> List<T> trim(List<T> input);
}
毕竟,您的修剪算法本身并不取决于类型 - 您可以使用同一实例来修剪 List<String>
和一个 List<Integer>
.
关于java - java中的自定义通用集合Trim类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15089295/