Alexander Mills
Alexander Mills

Reputation: 99959

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 better 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...

Upvotes: 4

Views: 25243

Answers (2)

stackoverflowuser2010
stackoverflowuser2010

Reputation: 40859

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();

Upvotes: 3

Bhupi
Bhupi

Reputation: 395

i am presuming here collection outer will not be null

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

CollectionUtils is a class from Apache API

[org.apache.commons.collections.CollectionUtils] .

it is safe and reliable.

Upvotes: 2

Related Questions