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?
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.
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.
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);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With