public
Created

demonstration of removing generic array warnings

  • Download Gist
RawTypeArrayFix.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
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];
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.