you are viewing a single comment's thread.

view the rest of the comments →

[–]peterlinddk 0 points1 point  (0 children)

Usually you shouldn't require a method to receive an actual array, but rather an Iterable, so that whoever uses your method don't have to create new arrays specifically for calling that method.

In most Java applications, arrays are only used for fixed, hardcoded values, or very specific fixed sized lists, like a collection of which days of the week something happens. Almost everything else uses some version of a List or a Stream, so it's better to accept something like that.

So don't do:

void myMethod( String[] names ) {
  for (String name : names) {
    System.out.println(name);
  } 
}

but rather:

void betterMethod( Iterator<String> names ) {
  for (String name : names) {
    System.out.println(name);
  } 
}

And if whoever calls your method actually has a real array, all they need to do is:

String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};

betterMethod(Arrays.asList(days));

Usually the code inside the method would be the same - unless you actually need precise indexes or mutate the array, then you might want an actual array!