I'm trying to make an insertion into an array of cells, but only when that cell is empty.
In my case, that would mean null
because I initialize an empty char array, and I want to insert only when the cell is empty (null
).
The test: if grid[i][j] == null
does not work, I get "== cannot be applied to 'char', null"
.
What is the proper way to do this?
Surelly to check if an array is null one would say (array == null) There's a key difference between a null array and an empty array. This is a test for null. int arr [] = null; if (arr == null) { System.out.println ("array is null"); }
There is no standard definition to define an empty array. We will assume an array is empty if Array is null. Array has no elements inside it. All the elements inside the array are null. To check if an array is null, use equal to operator and check if array is equal to the value null.
It doesn't matter that the array itself is empty. The null test in your post would only evaluate to true if the variable k didn't point to anything. I tested as below. Hope it helps. Integer [] integers1 = new Integer [10]; System.out.println (integers1.length); //it has length 10 but it is empty.
However, java/c# are more/less same. If you instantiate a non-primitive type (array in your case), it won't be null. In this case, the space is allocated & each of the element has a default value of 0. It will be null, when you don't new it up.
The "null" character is '\0'
, so you can compare if grid[i][j] == '\0'
.
The literal null
is for reference types, which char
is not.
Primitive arrays such as your char[][]
can't contain null
. Only object arrays can hold nulls. You could convert your array to Character[][]
instead.
Thanks to autoboxing your existing code should work just fine, but now you can actually put nulls in it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With