27

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?

Alex Kulinkovich
  • 4,408
  • 15
  • 46
  • 50
El Fuser
  • 441
  • 2
  • 6
  • 10

14 Answers14

35

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".

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • This is the problem: I have an array of arrays, say int x[][] = new int[20][3]. Using nested for loops I set the values in the innermost array to random numbers from 0 to 19. All is good so far, but i want a, where a is an index, to be an element of the x[elements of a]. For instance: if x[a] = {b,c,d} I want to get x[b]={a,...}, x[c]={a,..}, and x[d]={a,...}. But a may not necessarily be the first element of the array. Thanks very much for your help. – El Fuser Dec 14 '10 at 16:33
  • @El Fuser: I'm afraid I didn't follow that at all, to be honest... nor do I see what it has to do with your original question. – Jon Skeet Dec 14 '10 at 17:22
  • Sorry for the confusion, I guess what I am trying to say is that if you have int[] x = new int[3]; x[0]=1;x[1]=0; how can i know that x has only 2 elements that are not the initialization values. – El Fuser Dec 14 '10 at 19:11
  • @El Fuser: You can't. They're indistinguishable. All the elements in that case *are* the initialization values. – Jon Skeet Dec 14 '10 at 19:32
  • You may want a count later, in which case you'd pick jjnguy's solution. – HoldOffHunger Sep 18 '16 at 23:26
22

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.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
16

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.)

Gopi
  • 10,073
  • 4
  • 31
  • 45
jjnguy
  • 136,852
  • 53
  • 295
  • 323
6
  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.

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
khachik
  • 28,112
  • 9
  • 59
  • 94
4

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().

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
3

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

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
0

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.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
0

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.

prgmast3r
  • 413
  • 5
  • 8
0

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;
adimitri
  • 1,296
  • 9
  • 13
0

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;
   }
Brent Wilson
  • 213
  • 2
  • 3
0

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.

Ali Tohidi
  • 73
  • 7
0

You could also make it an Integer array. That way each item will be null. Then just count the number of non-null values. This still allows you to add ints, like you could before since Java does autoboxing and unboxing of primitives and their wrappers.

Integer[] numbers = new Integer[30];

int count = 0;
for (Integer num : numbers)
    if (num != null) count++;

System.out.println(count);
tazboy
  • 1,685
  • 5
  • 23
  • 39
-4

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

blalasaadri
  • 5,990
  • 5
  • 38
  • 58
uffes
  • 1
-5
int theArray[] = new int[20];
System.out.println(theArray.length);
Ram
  • 5