Alex Mills Alex Mills - 2 months ago 18
Java Question

Size of 2 dimensional ArrayList in Java

I have always found this to be problematic, essentially a guaranteed null pointer in most cases.

Say we have a two dimensional ArrayList, like so:

ArrayList<ArrayList<Integer>> outer;


Now, I want to get the dimensions of the inner arrays (we assume that they should all be the same size).

I often find that I do this:

int width = outer.size();
int length = outer.get(0).size();


but this is inherently unsafe and just horrible. What is a better way to do this?

One bad idea would be to iterate through all the array elements in the outer array, find the size of each inner array, make sure the sizes are all the same value, and then return that value, but that's a bit intensive.

Something like this:

private int getSizeOfInner(){

int size = null;

for(ArrayList<Integer> a: outer){
if(size == null){
size = a.size();
}
else{
if(a.size() != size){
throw new Exception("Inconsistent inner array sizes");
}

}
}
return size;
}


this seems pretty much overkill for this type of problem...

Answer
int length = outer.get(0).size();

but this is inherently unsafe and just horrible. What is a better way to do this?

Not sure what you mean by horrible. However, this is what I would do:

int length = outer.get(0) == null ? 0 : outer.get(0).size();