1

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 :(

5 Answers 5

3

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

}
Sign up to request clarification or add additional context in comments.

1 Comment

Derp, you're totally right. I was putting strings in my array cells and was just on a ".equals" kick. Works fine now! Thanks for the help.
1

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];

Comments

0

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.

Comments

0

Mixed up for loops and null construct

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

1 Comment

small correction: it's (int != null) there's an = too many there. Prly a typo. ;)
0

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.

1 Comment

It's going to be part of a table representation of a recursive parse tree. I could do a multi-dimensional array, but rather than maintain another integer through recursion, I'll just access the array name for that column.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.