Take the 2-minute tour ×

I have an integer array int[] a = new int [5].

In my code I am storing only 2 values at indices 0 and 1.

a[0]=100 and a[1]=101

Now I need to get the array size/length as 2.

What I should do?

share|improve this question
What's the wider context? Chances are there's a much better way of doing things than you've said here. –  berry120 Mar 8 '11 at 19:11
i dont know the size of the array initially. but after i store elemnts in my array i need to trim the array by removing unset indices –  athresh Mar 8 '11 at 19:14
add comment

5 Answers

You array length is 5, not 2. You've defined your array to be 5 elements long, how many you ended up using is irrelevant.

What can you do instead is this:

List<Integer> a = new ArrayList<Integer>();

will give you 2

share|improve this answer
add comment

You can't - there's no difference between an element which hasn't been set and an element which has been set to 0. The actual length of the array is 5, and will always be 5. (Arrays can't change in length after creation.)

Of course, if you know that you'll never use 0, you could write:

int size = 0;
for (int value : a)
    if (value != 0)

... but if you're trying to use the array as a buffer with a "live" segment at the start (like ArrayList does) then you'll have to maintain that size yourself.

share|improve this answer
+1 Personally I would have told exact same, but distinguishing primitive int from boxed type Integer, with what this is possible. –  Margus Mar 8 '11 at 19:16
add comment

You can not change the size of the array. However, you can make a new array with the correct size and copy the data you are interested in into the new array.

share|improve this answer
add comment

You could loop through the array and check the last index that isn't 0 - or if you use the Integer type you could do the same check but check for null instead of 0. But this won't give you the length, it's merely a poor estimate for how many values you've used.

A far better way would be to use an arraylist and then get the size of that. You're most likely using arrays for the wrong purpose here.

share|improve this answer
add comment

Use ArrayList or Vector .

Vector intvec = new Vector();
share|improve this answer
Please don't mention Vector as it's pretty much not used anymore. –  Steve Kuo Mar 8 '11 at 20:05
@Steve may be it is not, but still my favorite data structure. –  yogsma Mar 8 '11 at 20:15
add comment

Your Answer


