Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you count the elements of an array in java

Tags:

java

Say i have the array

int theArray = new int[20];

The length of the array is 20 but the count is 0. How can i get the count?

like image 403
El Fuser Avatar asked Sep 07 '25 16:09

El Fuser


1 Answers

What do you mean by "the count"? The number of elements with a non-zero value? You'd just have to count them.

There's no distinction between that array and one which has explicitly been set with zero values. For example, these arrays are indistinguishable:

int[] x = { 0, 0, 0 };
int[] y = new int[3];

Arrays in Java always have a fixed size - accessed via the length field. There's no concept of "the amount of the array currently in use".

like image 140
Jon Skeet Avatar answered Sep 10 '25 02:09

Jon Skeet