Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you represent something as empty in Java?

Tags:

java

arrays

I'm writing a Java program with an object containing an array and indices first and last to represent positions in the array where values are defined. So for instance if a double array of length 8 is supposed to be blank except at the 3rd, 4th, and 5th coordinates, like [_, _, _, -1.0, 4.2, -5.9, _, _] then first will store 3 and last will store 6 (one more than the last position where values are defined). However, I don't know how to have null values inside a Java array. It initializes everything to 0.0 and I'm not able to assign null values to any coordinates.

I'm required to use arrays for this task and an array of all 0.0s is supposed to be regarded as full, so I can't just choose to interpret that as empty.

Thanks for any help.

like image 394
Addem Avatar asked Feb 15 '26 07:02

Addem


2 Answers

You can use null to represent "undefined" for reference types. A double cannot be null (primitive type, not a reference type), but a Double can be. So you can use a Double[] instead of a double[].

But are you sure you need to be concerned about "undefined" values? It seems to me that it will be the responsibility of your data structure to know that any index below first and above last contains an undefined value. That is, without knowing the actual values stored at such indexes. The actual values stored there could be anything, shouldn't matter. That's the impression I'm getting from the little you revealed about the exercise, I may be wrong.

like image 104
janos Avatar answered Feb 16 '26 19:02

janos


If your array is of primitive type double[] then it can't be null. However Double[] (upper case) is an object wrapper for the primitive which allows null values.

like image 35
Drgabble Avatar answered Feb 16 '26 20:02

Drgabble



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!