【问题标题】:Filling an array with random vector2's in libGdx在 libGdx 中用随机向量 2 填充数组
【发布时间】:2016-05-20 16:58:25
【问题描述】:

当我在测试两个明显相似的代码时遇到问题时,我试图用随机向量 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);           
    }
}

第一个不起作用,只需用循环中生成的最后一个随机向量填充数组,即。数组中的所有向量都是相等的,第二个工作得很好,我的问题是,如果两个代码显然是等价的,为什么会发生这种情况。

【问题讨论】:

    标签: java arrays libgdx


    【解决方案1】:

    第一段代码不可能工作。仔细看看:

    Vector2 star = new Vector2();
    
    for (int i = 0 ;i <numStars ;i++){
        star.set(rand.nextInt(a),rand.nextInt(b));
        stars.add(star);           
    }
    

    您创建矢量ONCE,然后继续为其分配新坐标,然后将其添加到集合中。当您调用set() 时,您正在设置同一个向量的值(因为您仍然引用同一个向量)。

    结果是您在集合numStars 次中存储了相同的向量,这正是您所注意到的。

    也许为了更具体一点,您在第一个场景中创建的内容本质上是这样的:

    stars = [starA, starA, starA, ..., starA]
    

    第二个是这样的:

    stars = [starA, starB, starC, ..., starZ]
    

    如果您调用starA.set(),在第一种情况下,您不仅要修改要添加的星标;您正在修改您在其前面添加的每颗星(因为它们是同一颗星!)。

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      不,它们不相等。在 Java 中,当使用数据结构时,只传递 指针,而不传递实际的对象。

      因此,在您的第一个代码段中,您只有 一个 实际的 Vector2 对象,该对象被重复添加到 Array。因此,Array 中的每个元素都指向相同的对象,它们都将具有相同的值。这等于分配给star 变量的最后一个值。

      然而,第二个代码段确实有效,因为每个点都有自己的Vector2 对象,这意味着Array 中的每个元素都指向一个不同的对象在创建时随机分配自己的值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-04
        • 2011-01-23
        相关资源
        最近更新 更多