public Polynomial add(Polynomial other){
int max = Math.max(coefficients.length, other.coefficients.length);
int[] newPoly = new int[max];
for (int i=0; i<max; i++){
if (i<coefficients.length){
newPoly[i] += coefficients[i];
}
if (i<other.coefficients.length){
newPoly[i] += other.coefficients[i];
}
}
return new Polynomial(newPoly);
}
为什么这有效?索引
i
处的数组现在是否应该设置并且不可变,因为它是一个数组。那么,如果两个 if
语句都允许的话,为什么还要添加到索引呢。
这是我对代码的解释:
import java.util.*;
public class Stack{
public Polynomial add(Polynomial other){
// this finds the biiger polynomial of the two
int max = Math.max(coefficients.length, other.coefficients.length);
// this array is not going out of bounds of the bigger polynomial
int[] newPoly = new int[max];
// Go till the max
for (int i=0; i<max; i++){
// i should not go over the length of the smaller polynomial thefore there are 2 if statements
if (i<coefficients.length){
newPoly[i] += coefficients[i];
}
if (i<other.coefficients.length){
newPoly[i] += other.coefficients[i];
}
}
// then it makes a polynomial using the new arr
return new Polynomial(newPoly);
}
}
但基本上 i 从 0 开始直到 0 结束。我不确定你通过“ i 现在被设置并且不可变,因为它是一个数组”推断出什么。但是,是的,你是正确的,数组是不可变的,并且此方法绝不试图更改数组的大小。