tags:

views:

74

answers:

3

Here's the method I'm trying to write ( doesn't compile now, because what is not seen as an Iterable ):

public <T,V> ArrayList<V> mySelect(T what,ITest<V> x) {
     ArrayList<V> results = new ArrayList<V>();
     for(V value : what) {
        if(x.accept(value)) {
           results.add(value);
        }
     }  
     return results;
}

The T type implements Iterable , and returns V objects when using foreach. The thing is, I don't know how to write that. Can you help?

+4  A: 
public <T extends Iterable<V>,V> ArrayList<V> mySelect(T what, ITest<V> x) {

The logic behind: T is any subclass (implementing class in this case) of Iterable, and the Iterable is defined to iterate on V

I would recommend reading araqnid's suggestion, because it shows you how to make your code clearer.

Bozho
+4  A: 

Do you need to define T as a parameter type at all?

public <V> ArrayList<V> mySelect(Iterable<V> what, ITest<V> x) {

And it's usually good form to return the interface List rather than the implementation ArrayList.

araqnid
+1 for spotting other weak points
Bozho
Agreed on that, +1
Willi
+1  A: 

The way I would have written it. I wouldn't return an ArrayList explictly as the caller should know or expect a specific collection type.

public <V> List<V> mySelect(Iterable<V> what,ITest<V> x) {
     List<V> results = new ArrayList<V>();
     for(V value : what) 
        if(x.accept(value)) results.add(value);
     return results;
}
Peter Lawrey