基于这些评论,他们应该做同样的事情.除此之外,当我使用'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;
}
Run Code Online (Sandbox Code Playgroud)
那是一个,而另一个是:
/**
* 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];
}
}
Run Code Online (Sandbox Code Playgroud)
前者创建向量的副本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)
Run Code Online (Sandbox Code Playgroud)
但是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)
Run Code Online (Sandbox Code Playgroud)
虽然这两种方法执行相同的任务,但它们返回结果的方式不同:
PhysicsVector代表总和,且无副作用,只要v和u关注.这就是为什么从一种方法切换到另一种方法时会得到不同的结果.
result.add(u,v)好像不行
请注意,API的结构提供了正在发生的事情的提示,因为第一种方法是static.在实例上调用静态方法表示使用问题.你需要做的是
result = PhysicsVector.add(u, v);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
91 次 |
| 最近记录: |