When you work with a team of Java developers of varying experience levels, you will often see compiler warnings that are ignored by Java 5 — and thus just as often ignored by the developers who figure that if it isn’t important to Java, it isn’t important for them to fix either. I find the warnings quite annoying, and finally reached the point today where I decided to fix them (sending the developers a message as well).
Java 5.0 (aka “1.5”, aka “Tiger”) introduces “generics” — which provide a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection. Generics are a good thing. Omitting them will cause these ignorable, yet annoying and avoidable compiler warnings.
Problem #1:
“warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.ArrayList”
ArrayList arrUserInfo = new ArrayList(10); UserInfo userInfo = null; userInfo = createUserInfo(); arrUserInfo.add(userInfo);
The fix below tells the compiler that arrUserInfo
should expect only UserInfo objects.
ArrayList<UserInfo> arrUserInfo = new ArrayList<UserInfo>(m_pageSize);
Problem #2:
“warning: [unchecked] unchecked call to put(K,V) as a member of the raw type java.util.Hashtable”
private Hashtable env = new Hashtable(10); env.put("java.naming.ldap.factory.socket", "com.foobar.SSLSocketFactory");
Again, tell the compiler what type of objects to expect:
private Hashtable<String, String> env = new Hashtable<String, String>(10);
Problem #3:
Two different warnings about the same code. “warning: [unchecked] unchecked conversion” and “warning: [unchecked] unchecked method invocation: sort(java.util.List,java.util.Comparator) in java.util.Collections…”
public class FooBarOptionComparator implements Comparator {} public static void sortOptions(ArrayList<OptionItem> list) { Collections.sort(list, new FooBarOptionComparator()); }
Solution:
public class FooBarOptionComparator implements Comparator<Object> {}
It’s really nice to have fewer compile-time warnings!
If you’re still stuck, feel free to read more information about Java generics on Sun’s official documentation website.
Recent Comments