我有一个场景,我想将相同的逻辑应用于不同的类型。
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
}
}
有没有办法做到这一点?请告诉我。谢谢!