Skip to content

Instantly share code, notes, and snippets.

@rose00
Created December 2, 2011 22:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rose00/1425032 to your computer and use it in GitHub Desktop.
Save rose00/1425032 to your computer and use it in GitHub Desktop.
demonstration of removing generic array warnings
import java.util.List;
/*
* Test program to show how to remove warnings from generic array construction.
* First step: Remove any raw types, by adding <?> as needed.
* Second step: Add a cast if needed, to the specific non-wildcard type.
* Third step: Suppress "unchecked" warnings on the cast.
* The point of the first step is to remove the "rawtypes" warning
* cleanly, without resorting to an additional warning suppression.
* Note that every use of @SuppressWarnings should have a comment.
* Also, every @SuppressWarnings should be placed on the smallest
* possible program element, usually a local variable declaration.
*/
// To compile: $JAVA8_HOME/bin/javac -Xlint:all RawTypeArrayFix.java
class RawTypeArrayFix {
void test() {
{}
// warning: [rawtypes] found raw type: List
// warning: [unchecked] unchecked conversion
//QQ List<String>[] lss0 = new List[1];
// error: incompatible types
//QQ List<String>[] lss1 = new List<?>[1];
// warning: [unchecked] unchecked cast
//QQ List<String>[] lss2 = (List<String>[]) new List<?>[1];
// (clean)
@SuppressWarnings("unchecked") // array creation must have wildcard
List<String>[] lss3 = (List<String>[]) new List<?>[1];
// Bonus: No cast and now @SW is needed in some common cases:
List<?>[] lqs = new List<?>[1];
Class<?>[] cs = new Class<?>[1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment