I'm talking about Integer
object data type, not primitive int
Suppose this:
Integer[] arr = new Integer[5];
arr[0] = 2;
arr[1] = 2;
arr[2] = 3;
Then the array will look like this {2,2,3,null,null}
How can I get the size of the array? In this case, the size is 5
Same way as for any other array - you use the length
field:
int length = arr.length; // 5
From the JLS section 10.7:
The members of an array type are all of the following:
- The public final field
length
, which contains the number of components of the array. length may be positive or zero.- ...
If you want to count the non-null values, you'd use something like:
int count = 0;
for (Integer value : arr) {
if (value != null) {
count++;
}
}
(I'm sure there's a clever way to do this in fewer lines using the streams API in Java 8, but let's keep it simple for now...)
See more on this question at Stackoverflow