0

Here is a part of the code that I wrote.The output is really confusing me.I feel the code is pretty accurate.

List<List<Float>> deg_grp = new ArrayList<>();
List<Float> tempo = new ArrayList<>();
int u = 3;
for (int y = 0; y < 3; y++) {
    tempo.clear();
    for (int p = 0; p < u; p++) {
        System.out.println(p);
        tempo.add(p * 0.25f);
    }
    u++;
    System.out.println("--");
    deg_grp.add(tempo);
}
System.out.println(deg_grp);

and here is the output that I got:

0
1
2
--
0
1
2
3
--
0
1
2
3
4
--
[[0.0, 0.25, 0.5, 0.75, 1.0], [0.0, 0.25, 0.5, 0.75, 1.0], 
[0.0,   0.25, 0.5, 0.75, 1.0]]

I am really confused because I want the output to be like this: [[0.0,0.25,0.50],[0.0,0.25,0.50,0.75],[0.0,0.25,0.50,0.75,1.0]]

Kindly help me out. Thanks in advance :)

Tunaki
  • 132,869
  • 46
  • 340
  • 423

2 Answers2

1

Initialize tempo in the first loop. Clearing it is not a correct way. Since you always use same tempo array. You automatically change every element of list. You should check how list works

Ali sahin
  • 21
  • 3
1

You are always using the same list. So when you clear tempo and add items in it, you changes every entry in deg_grp.

In your first for loop, instead of clearing tempo you should assign it a new list.

Raphaël
  • 3,646
  • 27
  • 28