Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A very simple problem with ArrayList<int[]> 2

Status
Not open for further replies.

lellus

Technical User
Apr 25, 2009
2

Hi. I don't understand this strange behaviour.

import java.util.ArrayList;

public class Main {

public static void main(String[] args) {

int[] number = null;
ArrayList<int[]> numbers = null;

number = new int[1];
numbers = new ArrayList<int[]>();

for ( int value = 0; value<10 ; value++){
number[0] = value;
System.out.println(number[0]);
numbers.add(number);
}

//Output 0 1 2 3 4 5 6 7 8 9

for (int index = 0; index<numbers.size(); index++){
System.out.println(numbers.get(index)[0]);
}

//Output 9 9 9 9 9 9 9 9 9 9
}

Why the second output is different, why i have no store the sequence of numbers into Arraylist as vectors of integers?
Thanks
 
Arrays are reference types. So after the first loop, your arraylist will contain ten references to the same array.
 
The entries would reference the same object which finally settled in number[0]=9. Had only its clone be added each time, it wouldn't be the same.
>numbers.add(number);
[tt]numbers.add(number[blue].clone()[/blue]);[/tt]
 
yes yes yes
I'm very stupid!!
Thank you
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top