Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a method which would work on both lists and arrays?

Tags:

java

arrays

list

I have a method which looks like this:

void foo (List<String> list, ...) {
  ...
  for (String s : list) { // this is the only place where `list` is used
    ...
  }
  ...
}

the exact same code would work if I replace List<String> list with String[] list, however, to avoid spaghetti code, I keep the single method, and when I need to call it on an array a, I do it like this: foo(Arrays.asList(a)).

I wonder if this is The Right Way.

Specifically,

  • What is the overhead of Arrays.asList()?
  • Is there a way to write a method which would accept both arrays and lists, just like the for loop does?

Thanks!

like image 712
sds Avatar asked Dec 20 '22 20:12

sds


1 Answers

Arrays.asList() has a small overhead. There is no real way to implement one method for both List and arrays.

But you can do the following:

void foo (List<String> list, ...) {
  ...
  for (String s : list) { // this is the only place where *list* is used
    ...
  }
  ...
}

void foo (String[] arr, ...) {
  if ( arr != null ) {
      foo(Arrays.asList(arr),...);
  }
}
like image 109
Jérôme Verstrynge Avatar answered Jan 31 '23 00:01

Jérôme Verstrynge