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) {
result.addAll(collection):
}
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);
result.addAll(collection2):
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.
3 comments:
Re:
result.addAll(collection):
Q: Where is variable 'collection' came from? It's not defined anywhere.
Is it a typo?
collection2, вестимо.
Sure it's collection2. Thanks!
Post a Comment