Monday, September 04, 2006

expression of type X needs unchecked conversion

Ok, so you are using generics in Java but you also work with "legacy" code that has been written without generics. For example, you want to assign a return type ArrayList to a variable of type ArrayList .

Then you might experience a compiler warning similar to the following one:
Type safety: The expression of type List needs unchecked conversion to conform to List
As the compiler tries to statically check the type safety there is no way it can find out whether the raw type list actually contains only instances of YourType.

The solution is to add the following annotation in front of the method for which the warning is reported:
Note that the generic ArrayList<> is always compiled into the raw type ArrayList. The same applies for all other collections in java.util. The reason is that this type information is removed in order to stay backward compatible. Therefore in Java 5 all instances of ArrayList are mapped to the raw type ArrayList.

For C++ and also for .NET 2.0 and later the designers chose a different solution. In C++ each instance of the template ArrayList is compiled into separate object code. This can lead to code bloat. In .NET 2.0 and later the type information is retained and is available during runtime.

Sunday, August 20, 2006

Iterating Over Enum With Generic Method

Generic methods in Java 5 are nice, but sometimes it's good to have examples to better understand what is going on.

The following generic method iterates over an enum type and retrieves its values (ordinals, i.e. their underlying integer value) and their names:
protected void addType(Class clazz, Enum<?>[] enumValues) {
List<SelectItem> selectItems = new ArrayList<SelectItem>();
for(Enum<?> value : enumValues) {
SelectItem item = new SelectItem(value.ordinal(),,;
itemLists.put(clazz, selectItems);
The invocation of this method might be:
addType(RoleType.class, RoleType.values());
In this example RoleType is defined as a enum with one or more values.

Another option would have been to declare the method as:
protected <T extends Enum<T>> void addType(Class clazz, T[] enumValues) {...}
However, I decided that the code would look harder to read, so I used the wildcard version instead. Let me know if this example was helpful.

Monday, August 14, 2006

I've Moved

I moved over my Java blog from JRoller. That way it's easier to maintain the various blogs I have. So for my older posts on Java, please see my old Java blog.