I declare an array on dimension n, where n is the max number of elements that the array can contain:
int array[] = new int [n];
I have an algorithm that fills this array with values from 0 to maxValue. For example:
array[0] = 0;
array[1] = 1;
array[2] = 4;
array[3] = 5;
Let n = 8, if I print the array with:
System.out.println("array " + Arrays.toString(array));
I will have this output:
0 1 4 5 0 0 0 0
If I want check if there is the value 0 in the array, how can I do excluding the values that are derived from the initialization of the array? Basically i want consider just 0 1 4 5 and not 0 1 4 5 0 0 0 0.
This can be explained because if I have an array without value 0 for example:
array[0] = 3;
array[1] = 1;
array[2] = 4;
array[3] = 5;
Every element in the array that is not assigned, it will be 0. So for n=8 i will have 3 1 4 5 0 0 0 0 and if I check if the value 0 is in the array i will receive a positive.
You can't, basically - not based on just the array itself. There is no difference between a value which was explicitly set to 0 and one which just defaulted to 0.
You could change your array to be of type Integer[]
- then you'd have null
values for anything you haven't explicitly initialized. However, you wouldn't be able to tell the difference between those defaults and explicitly setting an array element to null...
See more on this question at Stackoverflow