根据评论,他们应该做完全相同的事情。除此之外,当我使用“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];
}
}
最佳答案
前者创建 vector v
的副本,增加它,然后返回该副本。后者实际上修改传递给它的原始 vector 。
所以:
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)
关于java - 这两种 PhysicsVector 方法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34002193/