Created
December 2, 2011 22:05
-
-
Save rose00/1425032 to your computer and use it in GitHub Desktop.
demonstration of removing generic array warnings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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