Hi, during the last days I have created several patches that introduce wildcards to generified collections. And very often I have to describe why this is necessary.
So I think it might be useful to discuss that topic once and for all. Java developers tend to avoid the wildcards (e.g. List<? extends Serializable>). I don't know exactly why, but most of the time people don't understand why those are necessary - so I try to describe it. List<? extends Serializable>: This declares *any* type of list that contains objects that implement Serializable. That could be a List of Strings or a List of Integers. We just don't know exactly. All we know is that the elements implement Serializable. Those Lists only offer read access. It is not possible to add any elements. Some example assignments: //contains all kinds of Serializables List<? extends Serializable> l = new ArrayList<Serializable>(); //contains *only* Strings List<? extends Serializable> l = new ArrayList<String>(); //contains *only* Integers List<? extends Serializable> l = new ArrayList<Integer>(); //contains *only* the given kind (that implments Serializable List<? extends Serializable> l = new ArrayList<*anything that implements Serializable*>(); List<Serializable>: This declares a list that contains Serializables - but *all* kinds of Serializables. So it is possible to store Strings *and* Integers (and all other objects that implement Serializable) within that list. It is *only* possible to assign a List<Serializable>: List<Serializable> l = new ArrayList<Serializable>(); It is *not* possible to assign those: List<Serializable> l = new ArrayList<String>(); !!!! DOES NOT WORK !!! So what is the problem now: If an interface method forces me to return a List<Serializable> it is *not* possible to return e.g. a List<String>. Instead I have to do fancy things to work around and be able to return that list. But there is just one simple rule that fits nearly every case: As long as you only *read* a collection or return an unmodifiable collection, *always* use wildcards. Only if you need or offer write access, it is necessary to specify a collection exactly. This discussion is necessary, since it is an incompatible change to add wildcards later. This will break your API! There are several bad examples out there that did this error (GlazedList anyone?). It is very hard to fix those issues afterward. So I strongly advice to do those things right before releasing 1.4. Regards, Johannes Schneider
smime.p7s
Description: S/MIME cryptographic signature
