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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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]}.