0

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?

5
  • 6
    Did you run the program and find out? Commented Sep 1, 2011 at 15:45
  • You can't. For this to know, you do not need to know Java, it's a logical matter unless you tolerate implicit allocations. Commented Sep 1, 2011 at 15:48
  • I've kind of figured it wouldn't work, so I was hoping someone would chime in with a way of doing this. I have tested this and it does not work. Edited for clarity. Commented Sep 1, 2011 at 15:51
  • It's like asking: How can I begin a life without having to be born? Commented Sep 1, 2011 at 15:54
  • Maybe you should review the title, because what you are asking doesn't make much sense. Collections hold object references always. Arrays hold references to variables (primitive or not). Commented Sep 1, 2011 at 15:55

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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.

Comments

0

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]}.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.