Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of 2 dimensional ArrayList in Java

Tags:

java

arraylist

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

like image 922
Alexander Mills Avatar asked Oct 29 '25 14:10

Alexander Mills


2 Answers

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();
like image 111
stackoverflowuser2010 Avatar answered Oct 31 '25 04:10

stackoverflowuser2010


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.

like image 25
Bhupi Avatar answered Oct 31 '25 03:10

Bhupi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!