Java
  Home arrow Java arrow Page 7 - Generics of Java 1.5 Tiger
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Moblin 
JMSL Numerical Library 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Generics of Java 1.5 Tiger
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 15
    2005-05-26

    Table of Contents:
  • Generics of Java 1.5 Tiger
  • Using Type-Safe Maps
  • Iterating Over Parameterized Types
  • Accepting Parameterized Types as Arguments
  • Returning Parameterized Types
  • Checking for Lint
  • Generics and Type Conversions
  • Using Type Wildcards
  • Writing Generic Types
  • Restricting Type Parameters

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Generics of Java 1.5 Tiger - Generics and Type Conversions


    (Page 7 of 10 )

    Now that you have all your nifty parameterized types, you’ll probably want to perform all sorts of nifty type conversions. This List of Integers gets tossed into that Map of Numbers...then again, it’s not quite that easy.

    You’ll need to take great care if you want these conversions to actually work.

    How do I do that?

    The key in casting generic types is to understand that as with normal, non-generic types, they form a hierarchy. What’s unique about generics, though, is that the hierarchy is based on the base type, not the parameters to that type. For example, consider this declaration:

      LinkedList<Float> floatList = new LinkedList<Float>();

    The conversion is based on LinkedList, not Float. So this is legal:

      List<Float> moreFloats = floatList;

    However, the following is not:

      LinkedList<Number> numberList = floatList;

    While Float is indeed a subclass of Number, it’s the generic type that is important, not the parameter type.

    What just happened?

    There are two key things to understand if you want to know why type conversions work like this; the first is seeing how type conversions can be abused, and the second is erasure. First, consider this sample code, which is actually illegal in Tiger; it demonstrates why converting a LinkedList<Float> to a LinkedList<Number> (or even to a LinkedList<Object>) should indeed be illegal:

      List<Integer> ints = new ArrayList<Integer>();
      ints.add(1);
      ints.add(2);
      // This is illegal, but use it for illustration purposes    List<Number> numbers = ints;
      // Now a float is being added to a list of ints! This results in a
      // ClassCastException when the item is retrieved from the
      // list and used as an int (instead of a float)  
      numbers.add(1.2);
      // This is even worse
      List<Object> objects = ints;
      objects.add("How are you doing?");

    Clearly, it needs to be the base type that is considered in type conversions, not the parameter type.

    The second concept you’ll want to grasp is erasure. Generics in Tiger is a compile-time process, and all typing information is handled at compile-time. Once the classes are compiled, the typing information is erased (thus the term erasure). Consider the following two declarations:

      List<String> strings = new LinkedList<String>();
      List<Integer> ints = new LinkedList<Integer>();

    This information is used at compile-time to perform type-checking, but then the typing information is dropped out at runtime. So, to the JVM, these declarations actually become:

      List strings = new LinkedList();
      List ints = new LinkedList();

    The type parameters are gone, now. With that in mind, consider this (illegal) cast:

      List<Integer> ints = new LinkedList<Integer>();
      List<Number> nums = ints;

    While this may look OK at compile-time, at runtime there are simply two lists, one trying to be cast to the other—without any type-safety in play at all. Again, then, the compiler does the right thing by using the base type, rather than the parameterized type, for cast checks.

    What about...

    ...defeating type-safety? Well, when you understand the reasons for casting restrictions and erasure, it actually becomes pretty easy to get around type checking. First, for backwards-compatibility, you can always cast a parameterized type to a raw type—that is, a generic type with no parameterization:

      List<Integer> ints = new LinkedList<Integer>();
      // We can widen (due to backwards compatibility)
      List oldList = ints;
      // This line should be illegal, but it happily compiles and runs
      oldList.add("Hello");
      // Here's the problem!
      Integer i = ints.get(0);

    This obviously leads to a ClassCastException at runtime, but it compiles just fine. You’ll get an unchecked warning (if you’re compiling under Tiger), but that’s it.

    Some folks get
    upset that
    parameterization
    is only a compile-
    time thing. A
    worthy gripe, but
    something (compile-time
    checking) is almost always better
    than nothing.

    You can also use erasure to break type-safety. Remember that at runtime, erasure removes all your parameterization. This means that when you access parameterized types with reflection, you get the effects of erasure, at compile-time (Example 2-1):

    Example 2-1. Breaking type safety with reflection

      package com.oreilly.tiger.ch02;
      import java.util.ArrayList;
      import java.util.List;
      public class BadIdea {
        private static List<Integer> ints = new ArrayList<Integer>();
        public static void fillList(List<Integer> list) {
          for (Integer i : list) {
            ints.add(i);
          }
        }
        public static void printList() {
          for (Integer i : ints) {
            System.out.println(i);
          }
        }
        public static void main(String[] args) {
          List<Integer> myInts = new ArrayList<Integer>(); 
          myInts.add(1);
          myInts.add(2);
          myInts.add(3);
          System.out.println("Filling list and printing in normal way...");
          fillList(myInts);
          printList();
          try {
            List list = (List)BadIdea.class.getDeclaredField("ints").get(null);
            list.add("Illegal Value!");
          } catch (Exception e) {
            e.printStackTrace();
          }
          System.out.println("Printing with illegal values in list...");
          printList();
        }
      }

    When list is assigned the reference of the ints List, it does not have the Integer restriction that the ints member variable does. As a result, adding a String value (like “Illegal Value!”) is perfectly legal—erasure has removed any parameterization. It’s only at runtime, when iterating over the list and printing it, that the problem shows up.

    More Java Articles
    More By O'Reilly Media


       · List<Integer> ints = new ArrayList<Integer>();ints.add(1);ints.add(2);// This...
       · public static int biggest(Box<T> box1, Box<U> box2) { int box1Size =...
     

    Buy this book now. This article was taken from chapter two of Java 1.5 Tiger: A Developer's Notebook, written by Brett McLaughlin and David Flanagan (O'Reilly, 2004; ISBN: 0596007388). Check it out at your favorite bookstore. Buy this book now.

    JAVA ARTICLES

    - Deploying Multiple Java Applets as One
    - Deploying Java Applets
    - Understanding Deployment Frameworks
    - Database Programming in Java Using JDBC
    - Extension Interfaces and SAX
    - Entities, Handlers and SAX
    - Advanced SAX
    - Conversions and Java Print Streams
    - Formatters and Java Print Streams
    - Java Print Streams
    - Wildcards, Arrays, and Generics in Java
    - Wildcards and Generic Methods in Java
    - Finishing the Project: Java Web Development ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...







    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway