Re: Polymorfic Collection construction
<acamposr@gmail.com> wrote in message
news:1146231735.021101.230440@g10g2000cwb.googlegroups.com...
Hello. I want to implement a method for filtering a class:
public Collection filter(Collection c) {
Collection filteredCollection = "An object of the same class that
c"
for(Object obj : c) {
if(satisfiesSomeCondition(obj))
filteredCollection.add(obj)
}
return filteredCollection;
}
As you see, I want to get any kind of Collection and create a new
collection (of the same type that the first one). How can I do that?
You could cop out and ask the user to provide you with the instance of
collection to populate.
<code tested="false">
public <T extends Collection> T filter(T collectionToReadFrom, T
collectionToPopulate) {
/*Weird things happen if collectionToReadFrom == collectionToPopulate*/
for(Object obj : collectionToReadFrom) {
if(satisfiesSomeCondition(obj)) {
collectionToPopulate.add(obj);
}
}
return collectionToPopulate;
}
....
ArrayList input = /*whatever*/;
ArrayList output = filter(input, new ArrayList());
</code>
- Oliver