[java] How do you count the elements of an array in 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?

This question is related to java

The answer is


int theArray[] = new int[20];
System.out.println(theArray.length);

  1. Your code won't compile, it should be int [] theArray = new int[20];;
  2. You can get the array length as theArray.length;
  3. For primitive types, the array will be initialized with the default values (0 for int).
  4. You can make it Integer [] theArray = new Integer[20]; and then count initialized members as this code does:

    public int count(Object [] array) {
        int c = 0;
        for(Object el: array) { if(el != null) c++; }
            return c;
    }
    

Please note that this answer isn't about why you may need this and what is the best way to do what you want.


You can use a for each loop and count the number of integer values that are significant. You could also use an ArrayList which will keep track of the couny for you. Everytime you add or remove objects from the list it will automatically update the count. Calling the size() method will give you the current number of elements.


There is no built-in functionality for this. This count is in its whole user-specific. Maintain a counter or whatever.


Iterate through it and count the elements which aren't null:

int counter = 0;
for (int i = 0; i < theArray.length; i ++)
    if (theArray[i] != null)
        counter ++;

This can be neatened up by using for:each loops and suchlike, but this is the jist.

Either that, or keep a counter and whenever you add an element, increment it.


Isn't it just: System.out.println(Array.length);? Because this is what it seems like you are looking for.


You can declare an array of booleans with the same length of your array:

true: is used
false: is not used

and change the value of the same cell number to true. Then you can count how many cells are used by using a for loop.


When defining an array, you are setting aside a block of memory to hold all the items you want to have in the array.

This will have a default value, depending on the type of the array member types.

What you can't do is find out the number of items that you have populated, except for tracking it in your own code.


If you wish to have an Array in which you will not be allocating all of the elements, you will have to do your own bookkeeping to ensure how many elements you have placed in it via some other variable. If you'd like to avoid doing this while also getting an "Array" that can grow capacities after its initial instantiation, you can create an ArrayList

ArrayList<Integer> theArray = new ArrayList<Integer>();
theArray.add(5); // places at index 0
theArray.size(); // returns length of 1
int answer = theArray.get(0); // index 0 = 5

Don't forget to import it at the top of the file:

import java.util.ArrayList;

Java doesn't have the concept of a "count" of the used elements in an array.

To get this, Java uses an ArrayList. The List is implemented on top of an array which gets resized whenever the JVM decides it's not big enough (or sometimes when it is too big).

To get the count, you use mylist.size() to ensure a capacity (the underlying array backing) you use mylist.ensureCapacity(20). To get rid of the extra capacity, you use mylist.trimToSize().


What I think you may want is an ArrayList<Integer> instead of an array. This will allow you do to:

ArrayList<Integer> arr = new ArrayList<Integer>(20);
System.out.println(arr.size());

The output will be 0.

Then, you can add things to the list, and it will keep track of the count for you. (It will also grow the size of the backing storage as you need as well.)


If you assume that 0 is not a valid item in the array then the following code should work:

   public static void main( String[] args )
   {
      int[] theArray = new int[20];
      theArray[0] = 1;
      theArray[1] = 2;

      System.out.println(count(theArray));
   }

   private static int count(int[] array) 
   {
      int count = 0;
      for(int i : array)
      {
         if(i > 0)
         {
            count++;
         }
      }
      return count;
   }