简体   繁体   中英

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. 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:

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

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

You should remove that j loop as your Foo is not a collection, it's a single object.

There's nothing wrong with your array. Just remove the j loop and you're good.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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