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?
Chris Uppal - 28 Apr 2006 15:24 GMT
> [...] 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?
It's harder than it looks.
The problem is that some implementations of Collection have configuration state
which is independent of the elements they contain. E.g. a TreeMap is
configured with a Comparator, and HashMaps have a load-factor. So, although
you could create an empty copy with:
Collection copy = (Collection)collection.getClass().newInstance();
that would not necessarily have the right Comparator.
Many of the standard Collections implementations do implement Clonable, and
clone() answers a shallow copy (presumably with the correct Comparator, etc).
So you could use that, and then try to remove the entries you don't want -- but
that will fail if the collection is not mutable (as is quite legal).
I don't think that a general, reliable, and easy-to-use solution is possible
given the Collections API.
-- chris
Patricia Shanahan - 28 Apr 2006 15:33 GMT
> Hello. I want to implement a method for filtering a class:
>
[quoted text clipped - 13 lines]
> 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?
java.util.Collections contains methods for creating checked (type safe)
or synchronized views of existing collections. Maybe the definitions and
implementations of those contain some useful techniques?
Patricia
Oliver Wong - 28 Apr 2006 21:30 GMT
> Hello. I want to implement a method for filtering a class:
>
[quoted text clipped - 13 lines]
> 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