example:
I want to see if array[5]
holds a value or is empty.
example:
I want to see if array[5]
holds a value or is empty.
There is no such thing as an "empty" element in a Java array. If the array's length is at least six, then element 5 exists and it has a value. If you have not assigned anything else to that location, then it will have the value zero, just like an object's uninitialized field would have.
If it is an array of Object
descendants, then you can check whether the element is equal to null
.
Elements in primitive arrays can't be empty. They'll always get initialized to something (usually 0 for int arrays, but depends on how you declare the array).
If you declare the array like so (for example)
int [] myArray ;
myArray = new int[7] ;
then all of the elements will default to zero.
An alternative syntax for declaring arrays is
int[] myArray = {12, 7, 32, 15, 113, 0, 7 } ;
where the initial values for an array (of size seven in this case) are given in the curly braces {}.
You have to define what you mean by empty. Depending on the datatype of the array you can decide on the semantics of empty. For example, if you have an array of ints you can decide that 0 is empty. Or if the array is of reference types then you can decide that null is empty. Then you simply check by comparing array[5] == null or array[5] == 0 etc.
Primitive arrays (int, float, char, etc) are never "empty" (by which I assume you mean "null"), because primitive array elements can never be null.
By default, an int array usually contains 0 when allocated. However, I never rely on this (spent too much time writing C code, I guess).
One way is to pick a value that you want to treat as "uninitialized". It could be 0, or -1, or some other value that you're not going to use as a valid value. Initialize your array to that value after allocating it.
Object arrays (String[] and any array of objects that extend Object), can have null elements, so you could create an Integer[] array and initialize it to nulls. I think I like that idea better than using a magic value as described above.
Create a constant to define the empty value, eg:
private static final int EMPTY = -1;
then create the array like this:
int[] myArray = new int[size];
Arrays.fill(myArray, EMPTY);
then to check if an element is 'empty', do this:
if (myArray[i] == EMPTY)
{
//element i is empty
}