Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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
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