0

I want to make an arraylist with int[] as objects

ArrayList<Integer[]> b= new ArrayList<Integer[]>(); Integer[] a= new Integer[2]; for(Integer i=0;i<20;i++){ a[0]=i; a[1]=i; b.add(a); } for(int i=0;i<20;i++){ System.out.println("line"+i+"= "+b.get(i)[0]+" "+b.get(i)[1]); } 

and the result I get is this

enter image description here

instead of the values( 0 0 1 1 etc), is seems that has saved only the last. I have also tried with type int instead of Integer but the same result

0

2 Answers 2

2

Consider initializing a within the loop as otherwise you are just writing over the same array the whole time. Instead of

ArrayList<Integer[]> b= new ArrayList<Integer[]>(); Integer[] a= new Integer[2]; for(Integer i=0;i<20;i++){ a[0]=i; a[1]=i; b.add(a); } for(int i=0;i<20;i++){ System.out.println("line"+i+"= "+b.get(i)[0]+" "+b.get(i)[1]); } 

consider this:

ArrayList<Integer[]> b= new ArrayList<Integer[]>(); for(Integer i=0;i<20;i++){ Integer[] a= new Integer[2]; a[0]=i; a[1]=i; b.add(a); } for(int i=0;i<20;i++){ System.out.println("line"+i+"= "+b.get(i)[0]+" "+b.get(i)[1]); } 

As the point is for each loop iteration to make a new array and store new values rather than overwrite the existing ones as if you step through your code you may notice you how don't ever allocate a new array within the loop.

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

1 Comment

thank you a lot it worked! I thought you simply add the inside of this object
2

You have to declare a new array for each element you're going to add. Otherwise they all reference the same memory. Declare the array inside the for loop instead of before the loop.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.