Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use a String array with a method taking an Iterable as a parameter?

I'm trying to write my own "functional" little lib in Java. If I have this function :

public static <T> List<T> filter(Iterable<T> source,BooleanTest predicate)
{
    List<T> results = new ArrayList<T>();
    for(T t : source)
    {
         if(predicate.ok(t))
            results.add(t);
    }
    return results;
}

why can't I use it with this snippet:

String strings[] = {"one","two","three"};
List<String> containingO = IterableFuncs.filter(strings,new BooleanTest() {
   public boolean ok(String obj) {
     return obj.indexOf("o") != -1;
   }
});

As far as I know, a Java array implements Iterable, right? What needs to be changed to make the function work with arrays, as well as collections? By choosing Iterable as the first parameter, I figured I got all cases covered.

like image 964
Geo Avatar asked Mar 16 '26 22:03

Geo


1 Answers

Arrays don't implement any interfaces in Java, unfortunately. The enhanced for loop works over arrays and iterables, separately.

However, you can use Arrays.asList(T...) to wrap an array in a List<T> which is iterable.

In terms of the "functional library" side of things, you should probably have a look at Google Collections which has a lot of similar stuff in.

like image 168
Jon Skeet Avatar answered Mar 19 '26 12:03

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!