Suppose an int[] is passed in, and I have function f(int[] array), if I don't know the length of array, how can I execute it chunk by chunk? or is there any better way do it? Thanks
Asked
Active
Viewed 345 times
1
-
1You do know the length of the array, it is `array.length` - Maybe you mean "How many elements were initialized with a different value then 0?" – amit Apr 01 '12 at 11:50
-
Is there any change the size of array is larger than Integer.Max_VALUE? – Jeffrey.W.Dong Apr 01 '12 at 11:58
-
1The size of the array cannot be bigger then `Integer.MAX_VALUE` – amit Apr 01 '12 at 12:00
5 Answers
3
In Java, you can get the length of the array from the array, simply by using:
int theArrayLength = array.length;

MByD
- 135,866
- 28
- 264
- 277
-
Is there any change the size of array is larger than Integer.Max_VALUE? – Jeffrey.W.Dong Apr 01 '12 at 11:55
-
@Jeffrey No. Since you index arrays by using ints that'd be somewhat useless ;) – Voo Apr 01 '12 at 12:02
2
What do you mean by "execute it" and "chunk by chunk"? You can always iterate over the array using an index.
for(int i = 0; i < array.length; i++) {
bar(array[i]);
}

andrunix
- 1,704
- 1
- 14
- 23
2
- Check if the array is
null
, and if so, throw an exception (e.g.IllegalArgumentException
) - Use enhanced for-loop
Example -
void f(int[] array){
if(array == null){
throw new IllegalArgumentException();
}
for(int arrayItem : array){
// iterate through array chunk-by-chunk
}
}
Using this approach, you can iterate through the array chunk-by-chunk without explicitly knowing the length of the array.

mre
- 43,520
- 33
- 120
- 170