1

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

Jeffrey.W.Dong
  • 1,057
  • 3
  • 14
  • 21

5 Answers5

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
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
  1. Check if the array is null, and if so, throw an exception (e.g. IllegalArgumentException)
  2. 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
1

doesn't java also know the arraya.length ?

Rps
  • 277
  • 1
  • 5
  • 25
0

You can find the length of any array in Java by doing

array.length
Waynn Lue
  • 11,344
  • 8
  • 51
  • 76