Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

letting a java function accept a collection or an array

I am trying to write a function that takes some strings and does something with them.

The only thing I'm going to do that the set of strings is loop over them. Right now I end up with an awkward construct along the lines of

public void foo(String[] myStrings){
    foo(java.util.Arrays.asList(myStrings));
}

public void foo(Iterable<String> myStrings){
    for(String i : myStrings){
        bar(i);
    }
}

which feels redundant since

for(String i : myStrings){
    bar(i);
}

would be perfectly valid code for myStrings of type String[].

Is there a class that I can have foo accept which will allow both collections and arrays?

like image 646
BostonJohn Avatar asked Dec 10 '12 18:12

BostonJohn


People also ask

Can you pass an array to a function in Java?

To pass an array to a function, just pass the array as function's parameter (as normal variables), and when we pass an array to a function as an argument, in actual the address of the array in the memory is passed, which is the reference.

What is the difference between array and collections in Java?

Arrays are fixed in size that is once we create an array we can not increased or decreased based on our requirement. Collection are growable in nature that is based on our requirement. We can increase or decrease of size. With respect to memory Arrays are not recommended to use.

How do you pass an array of objects to a function in Java?

Passing Array To The Method In Java To pass an array as an argument to a method, you just have to pass the name of the array without square brackets. The method prototype should match to accept the argument of the array type. Given below is the method prototype: void method_name (int [] array);

How do you pass an array to a collection in Java?

To convert array-based data into Collection based we can use java. util. Arrays class. This class provides a static method asList(T… a) that converts the array into a Collection.


1 Answers

See Why is an array not assignable to Iterable?

Short answer: no. Array types are synthetic code, as I understand it, and thus do not implement Iterable or any other types. You need to provide an overloaded method or require clients to call Arrays.asList at the call site.

like image 102
Thorn G Avatar answered Sep 17 '22 12:09

Thorn G