0

I have this code in Android Studio:

           for (ArrayList<Bitmap> arr : imgs) {
                for (Bitmap img : arr) {
                    if (img != null) {
                        arrayList.add(img.getHeight());
                    }
                    else {
                        arrayList.add(null);
                    }
                }
                heights.add(arrayList);
                arrayList.clear();
            }

With imgs declared and filled earlier and heights declared as an

ArrayList<ArrayList<Integer>>

What I get is:

[[58]]
[[null], [null]]
[[75], [75], [75]]
[[null], [null], [null], [null]]
[[1200], [1200], [1200], [1200], [1200]]
[[960], [960], [960], [960], [960], [960]]
[[960], [960], [960], [960], [960], [960], [960]]
[[612], [612], [612], [612], [612], [612], [612], [612]]
[[1632], [1632], [1632], [1632], [1632], [1632], [1632], [1632]]

And so on. Every time it doesn't add the value to the array but it replaces all the values in it with the new one. What's wrong?

1
  • 1
    ArrayList is working fine. Start by assuming it's your code that's not working. Commented May 8, 2016 at 12:22

1 Answer 1

3
heights.add(arrayList);
arrayList.clear();

You always add the same arrayList instance to heights, and you clear it, so all the previous values are lost.

You should create a new ArrayList instance in each iteration of the outer loop.

       for (ArrayList<Bitmap> arr : imgs) {
            arrayList = new ArrayList<Integer> ();
            for (Bitmap img : arr) {
                if (img != null) {
                    arrayList.add(img.getHeight());
                }
                else {
                    arrayList.add(null);
                }
            }
            heights.add(arrayList);
       }
Sign up to request clarification or add additional context in comments.

2 Comments

heights is the global Array<Array> and arrayList is the local Array. arrayList is updated, put into heights, and then cleared. Isn't it right?
@AndreaBR No, it's not. When you add arrayList to heights, you are not adding a copy of arrayList, you are just adding a reference to it. Therefore all the elements of heights refer to the same ArrayList.

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.