Menu

#23 CollectionUtils.transformedCollection does not work

v1.0 (example)
open
nobody
7
2014-08-14
2008-03-27
No

The output from CollectionUtils.transformedCollection is not correct, the items in the resulting collection are not transformed.

Try this simple testcase :

public class TransformCollectionTest extends TestCase {
public void testIterate() throws Exception {
List<Integer> l = Arrays.asList(1, 2, 3);
Collection<String> l2 = CollectionUtils.transformedCollection(l, new Transformer<Integer, String>() {

public String transform(Integer arg0) {
return "elt+" + arg0;
}
});
Iterator<String> it = l2.iterator();
for (int i = 1; i <= 3; i++) {
assertEquals("elt" + i, it.next());
}
}
}

Discussion

  • Michel Daviot

    Michel Daviot - 2008-03-27
    • priority: 5 --> 7
     
  • Gert van Valkenhoef

    I would like to add to this that TransformedCollection<I,O> breaks the generics contract by storing the transformed elements in the supplied Collection<I>. Obviously that should be a Collection<O>.

    In fact the current semantics of this method are very counter-intuitive as is illustrated by the above unit test (which *should* be broken according to the current Javadocs, but should not be considering the name of the method).

    What I would expect this method to do is actually implemented as a private method in TransformedCollection:
    protected Collection<O> transform(Collection<? extends I> coll) {
    List<O> list = new ArrayList<O>(coll.size());
    for (Iterator<? extends I> it = coll.iterator(); it.hasNext();) {
    list.add(transform(it.next()));
    }
    return list;
    }

     

Log in to post a comment.

MongoDB Logo MongoDB