简体   繁体   English

数组包含多个最后一个值

[英]Array contains multiple last values

I'm recently having an issue with adding values to an array. 我最近在将值添加到数组时遇到问题。
The array contains only multiple last values added. 该数组仅包含多个最后添加的值。
I was looking on Stack Overflow but all answers said either that a static field is used or there is the same object. 我一直在寻找Stack Overflow,但是所有答案都表明使用了静态字段或存在相同的对象。 But none of these are my case. 但是这些都不是我的情况。

Here's my code: 这是我的代码:

Main class: 主班:

public class Main {

    public static void main(String[] args) {
        Foo[] FooColection = new Foo[5];
        for (int i = 0; i < 5; i++) {
            Foo Bar = new Foo(i);//making a new Object everytime
            FooColection[i] = Bar;
            for (int j = 0; j < i;j++ ) {
                System.out.println(FooColection[i].getValue());
            }
        }
    }
}

Foo class: Foo类:

public class Foo {

    private int value;//non-static field

    public Foo(int value) {
        this.value = value;
    }

    public void change(int newVal) {
        this.value = newVal;
    }

    public int getValue() {
        return value;
    }
}

Output: 输出:

1
2
2
3
3
3
4
4
4
4

You are printing objects that many times. 您多次打印对象。 It is in j loop and you're printing with respect to i 它在j循环中,您正在针对i打印

System.out.println(FooColection[i].getValue());

You should remove that j loop as your Foo is not a collection, it's a single object. 您应该删除该j循环,因为Foo不是集合,它是单个对象。

There's nothing wrong with your array. 您的阵列没有任何问题。 Just remove the j loop and you're good. 只需删除j循环就可以了。

public class Main {

    public static void main(String[] args) {
        Foo[] FooColection = new Foo[5];
        for (int i = 0; i < 5; i++) {
            Foo Bar = new Foo(i);//making a new Object everytime
            FooColection[i] = Bar;
            System.out.println(FooColection[i].getValue());
            }
        }
    }
}

Output 产量

1
2
3
4

This behaviour is because of your nested loop, nothing else. 此行为是由于您的嵌套循环,没有别的。 Consider removing the nested loop and just print as you iterate. 考虑删除嵌套循环,然后在迭代时打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM