Find the length / size of an integer array

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

In my code, I only store 2 values ​​at indices 0 and 1.

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

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

What should I do?

+4
source share
5 answers

The length of the array is 5, not 2. You determined that your array has a length of 5 elements; how much you used does not matter.

What you can do instead:

 List<Integer> a = new ArrayList<Integer>(); a.add(100); a.add(101); System.out.println(a.size()); 

will give you 2

+9
source

You cannot - there is no difference between an element that has not been set and an element that has been set to 0. The actual length of the array is 5 and will always be 5. (Arrays cannot change length after creation.)

Of course, if you know you will never use 0, you can write:

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

... but if you are trying to use an array as a buffer with a live segment at the beginning (for example, an ArrayList ), you will have to maintain this size yourself.

+6
source

You cannot resize the array. However, you can create a new array with the correct size and copy the data that interests you into a new array.

+1
source

You can scroll the array and check the last index, which is not 0, or if you use the Integer type, you can do the same check, but check the null value instead of 0. But this will not give you the length, this is just a poor estimate of how much values ​​you used.

It would be best to use an arraylist, and then get the size of this. Most likely you are using arrays for the wrong purpose.

+1
source

Use ArrayList or Vector .

 Vector intvec = new Vector(); intvec.add(100); intvec.add(101); System.out.println(intvec.size()); 
+1
source

Source: https://habr.com/ru/post/1342874/


All Articles