Scriptico

Add to Google Reader or Homepage

Java Generics and Collections. Safe conversion

Are you working with Java? Have you ever seen the following warning message:

Type safety: The expression of type List needs unchecked conversion to conform to List<SomeClass>

I’ve seen it a lot. Technically, there is nothing wrong with this warning in most cases. The warning is related to API that either was built to support Java versions less than 1.5 or is a bit clumsy. Anyway, I do not really like any warnings in my code so I can’t ignore it. How to remove this warning?

The simple approach is to use the @SuppressWarnings annotation as shown below:

@SuppressWarnings("unchecked")
public List<Thing> getStuff() {
	Criteria criteria = getCurrentSession().createCriteria(Thing.class);
	return criteria.list();
}

The @SuppressWarnings annotation indicates that the named compiler warnings should be suppressed in the annotated element. It is easy as ABC, isn’t it? Although the approach is suitable for 99.99% cases, a lot is going on out of our vision.

The second approach is clearer and shows that a developer knows what is happening, why and how to avoid it.

public List<Thing> getThings() {
	Criteria criteria = getCurrentSession().createCriteria(Thing.class);
	return castCollection(criteria.list(), Thing.class);
}
public static <E> List<E> castCollection(Collection<?> collection,
		Class<? extends E> clazz) {
	List<E> result = new ArrayList<E>(collection.size());

	for (Object current : collection) {
		result.add(clazz.cast(current));
	}
	return result;
}

Unfortunately, there is a negative part of the approach: your code will iterate over the received collection every time. I like this approach being safe, yet I am not ready to pay this price. How about you?

Category: Development, Java

Tagged:

Comments are closed.