Why you should only return Collections with bounded wildcards
- January 12th, 2008
- Posted in Generics . Java
- Write comment
My post yesterday did not receive much compliance.
Many agreed, that collections with wildcards are usefull as method parameters, most deny their value as type for return values
That’s why I have created a small example that displays the problems not using wildcards. Unfortunately these problems are not very obvious and appear late. Besides that, most of the time the caller has to puzzle with it and maybe you will never hear about it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public interface TightList<E> { List<E> getIt(); } final TightList<Integer> integerList = new TightList<Integer>() { public List<Integer> getIt() { return new ArrayList<Integer>(); } }; final TightList<Double> doubleList = new TightList<Double>() { public List<Double> getIt() { return new ArrayList<Double>(); } }; TightList<Number> wrapping = new TightList<Number>() { public List<Number> getIt() { if ( someFancyCondition ) { return doubleList.getIt(); //Compiler error } else { return integerList.getIt(); //Compiler error } } }; |
I think it is quite obvious what happens here.
We have a simple interface called “TightList” that returns a collection without bounded wildcard. I created three implementations. The first two of them are straight forward – no problems occur here.
But the third one becomes critical. Wrapping the other TightLists is not possible.
Conclusion
There is at least one case, where returning collections without wildcard, is problematic.
Please, oblige the users of your API and add those wildcards (at least when the collection is unmodifiable – and it really should be).
No comments yet.