Unchecked Conversion Warnings

This post is taken from an email sent round by Jim Downing following a PMR group code review meeting. The topic which caused the most problem was how to remove unchecked conversion warnings from eclipse which were greatly upsetting a few members of the group (not me).

Primarily I just wanted to capture this for reference rather than keeping it in my inbox.

Had a bit of a dig around the unchecked conversion issue.
The solutions to the problem, in my opinion and in Miss World order: -

  1. I think the _worst_ thing to do is the default eclipse behaviour; adding @SuppressWarnings(“unchecked”) to the method declaration, since this will mask other warnings too, some of which can be much more severe than this one.
  2. The next worst thing to do is to suppress warnings by annotating the individual line. I dislike this one because the annotation is just distracting noisy cruft.
  3. Live with it. Stop your IDE whinging about it so much – the code will still compile.
  4. The best solution is given in the answer at

http://stackoverflow.com/questions/367626/how-do-i-fix-the-expression-of-type-list-needs-unchecked-conversion/367673#367673

The main point in the answer given above is that doing an unchecked conversion results in the ClassCastException coming from the guts of the compiled code somewhere, rather than from your code, which is a Bad Thing. So the best thing to do is: -

Rather than : -
List<String> whatYoudLike = foo.getUntypedList(); // Exception gets thrown from the guts of whatever the compile generates to do this.

for(String s: whatYoudLike) {
//
}

the best way to do it would be: -

for(Object o : foo.getUntypedList()) {
String s = (String) o; // Exception gets thrown here if at all.
//
}

This approach can get a bit more verbose, but that is, I’m afraid, tough luck.

One Response to “Unchecked Conversion Warnings”

  1. Unchecked Type Conversion best practice « Jim Downing Says:

    [...] generics. I should probably have posted it myself, but Joe has done me the service of recording the results of our discussion and research. Posted in Uncategorized | Leave a Comment [...]

Leave a Reply