bwoogie
bwoogie

Reputation: 4427

ArrayList losing items

Is there a reason why an ArrayList would just lose items? I have an ArrayList that holds ArrayLists which holds Integers. There are about 32 items in each. Later when I need to call the ArrayList the items are missing except the last one. There are still 32 items, but they're empty.

[[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [-16323110, -16688166, -14978279, -837220, -11002320, -4136419, -13118245, -5370572, -11382698, -13140399, -13754890, -8184649, -11711035, -11668025, -12910969, -11058211, -9974559, -9665946, -12513105, -14320755, -16332438, -7673092, -13016023, -15454286, -12413148, -9780316, -2553149, -3313219, -10953060, -940790, -11989718, -12189591]]

I'm able to read it once and everything is there... but later when i call it again it's gone. I'm not removing anything. What is happening here?

I cant post my original code but heres a mock up.

private ArrayList<ArrayList<Integer>> myArray = new ArrayList<ArrayList<Integer>>();

private void makeArray() {
for(int i = 0; i<= _height - 1; i++) {
            ArrayList<Integer> row = new ArrayList<Integer>();
            for(int ii = 0; ii <= _width - 1; ii++) {
                row.add(ii);    
            }
            myArray.add(row);
        }
}

private void readArray() {
ArrayList<Integer> row = new ArrayList<Integer>();

            for(int a = 0; a <= _height - 1; a++) {
                row.clear();
                row = myArray.get(a);

                for(int aa = 0; aa <= _width - 1; aa++) {
                    int c = row.get(aa);
//stuff
                }
            }
}

Upvotes: 1

Views: 1537

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500055

Look at your code:

private void readArray() {
    ArrayList<Integer> row = new ArrayList<Integer>();

    for(int a = 0; a <= _height - 1; a++) {
        row.clear();
        row = myArray.get(a);
        ...
    }
}

At the start of each iteration, you're clearing the ArrayList you were looking at in the last iteration. Why would you do that?

Just get rid of the row.clear() call, and I'd expect everything to be fine. I'd also suggest using the rather more idiomatic:

for(int a = 0; a < _height; a++) {

Or even better:

for(int a = 0; a < myArray.size(); a++) {

Or even better:

for (ArrayList<Integer> row : myArray) {
    ...
}

(Then you don't need to call myArray.get() at all!)

Upvotes: 5

Related Questions