开发者

Storing an array to an ArrayList without allocating another array?

Consider this example:

int[] a = new int[] {0,0};
ArrayList<int[]> b = new ArrayList<int[]>();

b.add(a);
a[0] = 1;
a[1] = 1;开发者_StackOverflow社区
b.add(a);

b is now {[1,1],[1,1]}. How can I ensure it will be {[0,0],[1,1]} without allocating another array?


It just adds the reference. So it will be {[1,1],[1,1]}. I don't think there is another solution other than allocating another array.


without allocating another array

Well, you want to have two independent sets of values at the same time. This requires two arrays (or two lists etc).


An array is an object. If you change the array, it doesn't matter how many times you added it to the list, the toString will show the most recent state of the array. The list's toString iterates on his elements and calls toString on each one. I don't know what are you trying to do, but maybe you should read some basic tutorials.


Each element of an ArrayList<int[]> is a reference to an array of ints. If you add the same array twice (as you are doing), it will be repeated in the list. Changing an element of the int array will be reflected in every occurrence of it in the ArrayList. To have different arrays, you need to have separate arrays allocated. Something like this will do:

int[] a = new int[] {0,0};
ArrayList<int[]> b = new ArrayList<int[]>();

b.add(a.clone()); // add a distinct array
a[0] = 1;
a[1] = 1;
b.add(a);

Then the contents of b will be {[0,0],[1,1]}.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜