When I find something interesting and new, I post it here - that's mostly programming, of course, not everything.

Thursday, December 04, 2008

Java Compiler Warnings 1

Since out of the 5 million Java programmers there's hardly 100 that actually know Java (I do not count myself in that holy hundred), we probably have to join our efforts (like people do at javaranch and help each other.

Here I'm going to post typical Java Compiler warnings that I encounter and fix.

So this chain letter is something like "effective java for dummies", so to say.

1. Creating generic arrays.

Out of your best intentions, you decide that instead of manually concatenating your collections, you'll have something like this:

Collection<T> concat(Collection<T>... collections) {
Collection<T> result = new ArrayList<T>();
for (Collection<T> collection : collections) {
return result;

Let's forget the dubious decision of making a live arraylist out of collections of unknown nature, instead of just having a lazy collection or iterable. What's the problem here? Will our compiler complain? No. But if we try to use it, like this:

Collection<Integer> newCollection(oldCollection1, oldCollection2);

we will get a compiler warning: "generic array creation" warning. What's wrong? Here's what. When you pass around a vararg list of parameters, implicitly an array is being created. But Java does not like creating arrays of elements which type is generic. Hence the warning.

To avoid, we can just write a simpler version:

Collection<T> concat(Collection<T> collection1, Collection<T> collection2) {
Collection<T> result = new ArrayList<T>(collection1);
return result;
Collection<Integer> newCollection(oldCollection1, oldCollection2);

Not that I neither condone nor discuss the idea of building an arraylist - this deplorable issue is just outside of the narrow boundaries of this topic.


Vitaliy said...


Q: Where is variable 'collection' came from? It's not defined anywhere.
Is it a typo?

Dmitry said...

collection2, вестимо.

Vlad Patryshev said...

Sure it's collection2. Thanks!


Subscribe To My Podcast