将数组存储到 ArrayList 而不分配另一个数组?
考虑这个例子:
int[] a = new int[] {0,0};
ArrayList<int[]> b = new ArrayList<int[]>();
b.add(a);
a[0] = 1;
a[1] = 1;
b.add(a);
b 现在是 {[1,1],[1,1]}。 如何确保它是 {[0,0],[1,1]} 而不分配另一个数组?
Consider this example:
int[] a = new int[] {0,0};
ArrayList<int[]> b = new ArrayList<int[]>();
b.add(a);
a[0] = 1;
a[1] = 1;
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它只是添加参考。所以它将是
{[1,1],[1,1]}
。我认为除了分配另一个数组之外没有其他解决方案。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.那么,您希望同时拥有两组独立的值。这需要两个数组(或两个列表等)。
Well, you want to have two independent sets of values at the same time. This requires two arrays (or two lists etc).
数组是一个对象。如果更改数组,无论将其添加到列表中多少次,toString 都会显示数组的最新状态。
列表的 toString 迭代其元素并对每个元素调用 toString。
我不知道你想做什么,但也许你应该阅读一些基本教程。
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.
ArrayList
的每个元素都是对 int 数组的引用。如果您将同一数组添加两次(正如您所做的那样),它将在列表中重复。更改 int 数组的元素将反映在 ArrayList 中该元素的每次出现中。要拥有不同的数组,您需要分配单独的数组。像这样:然后 b 的内容将是 {[0,0],[1,1]}。
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:Then the contents of b will be {[0,0],[1,1]}.