Java的类型系统根本无法表达这一点。这是一个解决方法。
创建提供了数字运算你有兴趣的接口Numeric
,并写入它的实现你感兴趣的数据类型。
interface Numeric<N> {
public N add(N n1, N n2);
public N subtract(N n1, N n2);
// etc.
}
class IntNumeric extends Numeric<Integer> {
public static final Numeric<Integer> INSTANCE = new IntNumeric();
private IntNumeric() {
}
public Integer add(Integer a, Integer b) {
return a + b;
}
public Integer subtract(Integer a, Integer b) {
return a - b;
}
// etc.
}
和重写你的Matrix
类的构造函数接受这个执行。
class Matrix<N> {
private final Numeric<N> num;
private final List<List<N>> contents;
public Matrix(Numeric<N> num) {
this.num = num;
this.contents = /* Initialization code */;
}
public Matrix<N> add(Matrix<N> that) {
Matrix<N> out = new Matrix<N>(num);
for(...) {
for(...) {
out.contents.get(i).set(j,
num.add(
this.contents.get(i).get(j),
that.contents.get(i).get(j),
)
);
}
}
return out;
}
}
// Use site
Matrix<Integer> m = new Matrix<Integer>(IntNumeric.INSTANCE);
希望有所帮助。
'Cat'扩展'Animal','Dog'是'Animal'的一个子类。这并不意味着你可以返回一个'狗',其中预计有'猫'。 –
@OliCharlesworth我已经尝试过铸造到T,但是这似乎没有帮助 –
@NuclearGhost:这给了什么错误? – SLaks