Unchecked Variables tutorialFrom WikiJavabuy this book
This tutorial explains how to properly use the generics in order to avoid unchecked variables and related errors in Java 5 and newer.
the articleIn this tutorial I will show you the right way to use the generics in Java 5 and newer in order to avoid the warning about unchecked variables produced at compilation time. One of the main improvements in Java5 was the introduction of the generics, by which you can avoid explicitly casting the objects to specific classes when you get them out of a collection. The procedure was very error prone and uncomfortable. In Java 5 with the generics you can specify what kind of objects your collection will hold. The syntax to do it is as in the following example: List<String> listString = new ArrayList<String>(); Then when you will retrieve an element from listString it will already be a java.lang.String and there won't be the need of an explicit casting. the following program executes two methods unchecked and checked.
the code
package com.javawiki.generics; import java.util.ArrayList; import java.util.List; /** * @author Giulio * @date 11/12/2007 */ public class Unchecked { /** * */ @SuppressWarnings("unchecked") public static void unchecked() { List a = new ArrayList(); a.add(new String("uncheck")); // explicit cast is needed System.out.println("string: '" + (String) a.get(0) + "'"); try { // you can cast to a wrong type, and get a lot of troubles from it. System.out.println("string: '" + (Integer) a.get(0) + "'"); } catch (Exception e) { System.out.println(); e.printStackTrace(); System.out.println(); } } /** * */ public static void checked() { List<String> a = new ArrayList<String>(); // the methods of ArrayList accept only String objects a.add(new String("checked")); // // a.add(new Integer(22)); // this line would give you a compilation problem // a.get(0) is already a String object no cast is needed System.out.println("string: '" + a.get(0) + "'"); } /** * @param args */ public static void main(String[] args) { unchecked(); checked(); } } See Also
|
