V1rtua1An0ma1y
V1rtua1An0ma1y

Reputation: 627

Checking Array for null element

So I've created my own class with 5 private fields: Each is an array with a pre-set length. It's my way of creating a table, where each array is a column, and they have pre-set lengths because not every cell will contain an element (So, not using anything dynamic).

Anyway, my question is: Can I check to see if a specific cell of a specific array contains "null"? Using .equals(null) gives a nullpointerexception :(

Upvotes: 1

Views: 265

Answers (5)

user000001
user000001

Reputation: 33317

When you call .equals(...) you call a method of the object. If it is null, it has no method. Therefore null check like this:

if (myArray[position] == null) {
    ....

}

Upvotes: 3

ObedMarsh
ObedMarsh

Reputation: 433

I'm more curious as to why your making 5 arrays? Have you heard of multidimensional arrays? Maybe that's what you really need in this case.

an array like this fx: int[][] arrayName = new int[3][3];

Would represent an array of 3 rows and 3 columns in each.

Maybe you alrdy knew that, but it just seems weird to me to make five different arrays if you just want a table-like structure.

Upvotes: 0

Starx
Starx

Reputation: 78971

Mixed up for loops and null construct

for(Integer ints : intNum) {
    if(intNum != null) {
      //valid
    }
} 

Upvotes: 0

Ignacio Quintero
Ignacio Quintero

Reputation: 143

you should use

if (cell[i] == null){


}

since you are testing for reference equality. And in the case where cell[i] is actually null, null doesnt have an equals method.

Upvotes: 0

Miguel Prz
Miguel Prz

Reputation: 13792

don't do .equals(null) but == null:

if( the_array[i] == null ) {
  //...
}

Think about build a table by a bidimensional array. Example:

TheClass my_array[][] = new TheClass[10][5];

Upvotes: 1

Related Questions