I hope you are having fun with the example. Java creates an empty array and then you can access the elements with indexOf(). You can also access the elements as a set.
java.lang.ArrayIndexOutOfBoundsException is one of the most common reasons to ask “Why do I need an array?” When Java creates an empty array, it will throw an exception because the length of the array is 0. This makes sense when you think about it because you can’t have any more elements in an array.
Java has another way to accomplish the same thing, but it is not as common. Java has a method called arraySize that gives you the number of elements in an array. I think that is a much cleaner method when you think about it because if you have an array with 0 elements and you try to access one of them, it will throw a runtime error.
arraySize is a better method because it also works with primitives, such as double and String (which are not objects). The reason it was a little easier to use in the first place is because arrays are objects, so this method was actually created by the Java designers specifically for this case.
The arraySize method is also more readable.
There’s no reason to create an array just to store a null value in java.
Another problem with creating a new array each time you want to access a value is that they are stored in memory one at a time. If you have a million elements in a array and you need to access just one, you have to access every element individually. That’s not a big deal, but it makes it difficult to find things when you want to do a lot of calculations.
Creating an array each time you want to do a calculation is a common mistake, but it is not that common. It is also really easy to fix. Simply declare a new java.lang.Boolean field and use that field as a defaultValue for each element. This will give you a single field that is always non-null. Even if there are only 10 elements in the array, you can now use the defaultValue to access them.
I’m sure you’ve seen the code I wrote for this when I ran into an error. But that’s not my whole explanation, so here’s the rest: If you have a single large number that you need to store and use as a default value, you need to declare a new java.lang.Boolean field and use that field as the default value of each element.
We’ve been using the java.lang.Boolean for a long time in our project and it always works great.