根据评论,他们应该做完全相同的事情。除此之外,当我使用“ add”而不是“ increaseBy”时,我的代码会产生不同的输出。

/**
* standard vector addition. If <b> v = xi + yj</b>
* and <b>u = wi + zy</b>, then the method returns a vector
* <b>(x+w)i + (y+z)j</b>
*
* @param v first vector in sum
* @param u second vector in sum
* @return return summed vector
**/
public static PhysicsVector add(PhysicsVector v, PhysicsVector u){
    PhysicsVector sum = new PhysicsVector(v);
    sum.increaseBy(u);
    return sum;
}


所以这是一个,这里是另一个:

/**
* Add a vector <b>v</b> to the original vector. Normal vector
* addition is carried out. I.e. the x-components are added and
* the y components are added, etc.
*
* @param v vector to be added to original vector.
**/
public void increaseBy(PhysicsVector v){
    for (int i=0; i<vectorComponents.length; i++) {
        vectorComponents[i] += v.vectorComponents[i];
    }
}

最佳答案

前者创建向量v的副本,将其增加,然后返回该副本。后者实际上修改了传递给它的原始向量。

所以:

PhysicsVector u = new PhysicsVector(1, 1);
PhysicsVector v = new PhysicsVector(2, 4);

PhysicsVector result = PhysicsVector.add(u, v);

// u and v are still (1, 1) and (2, 4), and result is (3, 5)


但是使用increaseBy

PhysicsVector u = new PhysicsVector(1, 1);
PhysicsVector v = new PhysicsVector(2, 4);

u.increaseBy(v);

// u itself has now been changed to (3, 5)

09-08 08:01