当我试着用随机向量2填充数组“星星”时,我在测试两个明显相似的代码时遇到了问题。
头
Array<Vector2> stars;
int numStars;第一法典
public void initStars() {
int a = 100;
int b = 120;
numStars = (int) (a * b * 0.01f);
stars = new Array<Vector2>(numStars);
Random rand = new Random();
Vector2 star = new Vector2();
for (int i = 0 ;i <numStars ;i++){
star.set(rand.nextInt(a),rand.nextInt(b));
stars.add(star);
}
}第二守则
public void initStars() {
int a = 100;
int b = 120;
numStars = (int) (a * b * 0.01f);
stars = new Array<Vector2>(numStars);
Random rand = new Random();
for (int i = 0 ;i <numStars ;i++){
Vector2 star = new Vector2();
star.set(rand.nextInt(a),rand.nextInt(b));
stars.add(star);
}
}第一个不起作用,只需用循环中生成的最后一个随机向量填充数组,即。数组中的所有向量都是相等的,第二个向量工作得很完美,我的问题是,如果这两个代码显然是等价的,为什么会发生这种情况。
发布于 2016-05-20 17:01:27
第一段代码不可能工作。仔细看看:
Vector2 star = new Vector2();
for (int i = 0 ;i <numStars ;i++){
star.set(rand.nextInt(a),rand.nextInt(b));
stars.add(star);
}创建向量一次,然后继续为其分配新的坐标,然后将其添加到集合中。当您调用set()时,您将设置相同向量的值(因为您仍然引用相同的向量)。
结果是,在集合numStars时间中存储相同的向量,这正是您注意到的。
也许为了使这个更加具体,您在第一个场景中创建的本质是:
stars = [starA, starA, starA, ..., starA]第二个问题是:
stars = [starA, starB, starC, ..., starZ]如果您调用starA.set(),在第一种情况下,您不仅要修改要添加的星星,而且还要修改--在它前面放置的每个星星--(因为它们是同一颗星!)
希望这能有所帮助。
发布于 2016-05-20 17:07:08
不,它们不是等价物。在Java中,当使用数据结构时,只传递指针,而不是实际的对象。
因此,在第一个代码段中,只有一个实际的Vector2对象,该对象被重复添加到Array中。因此,Array中的每个元素指向同一个对象,它们都具有相同的值。这等于分配给star变量的最后一个值。
但是,第二个代码段确实有效,因为每个点都有自己的对象,这意味着Array中的每个元素指向一个不同的对象,该对象在创建时具有自己的随机赋值。
https://stackoverflow.com/questions/37352060
复制相似问题