2 回答

TA貢獻1890條經驗 獲得超9個贊
最簡單的方法似乎是在Vector類上有一個實例方法:
Vector make(double[] values) {
return new Vector(values);
}
然后在每個子類中覆蓋它,使用協變返回類型:
class Vector3 extends Vector {
//...
@Override Vector3 make(double[] values) {
return new Vector3(values);
}
//...
}
然后你可以在你的 multiply 方法中調用它。
return vector.make(values);
但老實說,我不會嘗試將向量的長度編碼為類型。當你需要一個包含 57032 個元素的向量時會發生什么?您肯定不想為此創建一個特定的類,對嗎?如果您有兩個Vector具有相同數量元素的不同子類,會發生什么情況:它們是否兼容(例如相加)?
更自然地處理向量的語言(例如 MATLAB)不會將其構建到類型中;問問自己是否真的需要這里。

TA貢獻1936條經驗 獲得超7個贊
如果它對性能至關重要,您實際上可能會考慮讓 multiply 方法改變向量的狀態,而不是創建一個新的。在我看來,這并不奇怪,只要它是確定性的和記錄在案的行為即可。
但是,對于不可變向量類,您需要clone
向量。
public class Vector implements Cloneable {
? ? // not a good idea to make it public, if you don't want any changes here
? ? private double[] values;
? ? public static <T extends Vector> T multiply(T vector, double k) {
? ? ? ? Vector temp = vector.clone();
? ? ? ? for(int i = 0; i < temp.values.length; i++)
? ? ? ? ? ? temp.values[i] = k * temp.values[i];
? ? ? ? // the clone method guarantees that 'temp' is of type T,
? ? ? ? // but since it is not generic, the compiler cannot check it
? ? ? ? @SuppressWarnings("unchecked")?
? ? ? ? T result = (T)temp;
? ? ? ? return result;
? ? }
? ? protected Vector clone() {
? ? ? ? try {
? ? ? ? ? ? Vector vector = (Vector)super.clone();
? ? ? ? ? ? vector.values = Arrays.copyOf(values, values.length);
? ? ? ? ? ? return vector;
? ? ? ? } catch (final CloneNotSupportedException exc) {
? ? ? ? ? ? // this is a weird design choice of `Object.clone()`, too,
? ? ? ? ? ? // but back then, we did not have annotations or anything equivalent
? ? ? ? ? ? throw new AssertionError("we forgot to implement java.lang.Cloneable", exc);
? ? ? ? }
? ? }
}
添加回答
舉報