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