Home arrow Java arrow Page 7 - Generics of Java 1.5 Tiger
JAVA

Generics of Java 1.5 Tiger


The generics feature of Tiger brings greater type safety to Java, allowing developers to do many things they could not do before. Generics bear on a number of other features specific to Tiger. This article introduces you to generics, and what they can do. It is excerpted from chapter two of Java 1.5 Tiger: A Developer's Notebook, written by Brett McLaughlin and David Flanagan (O'Reilly, 2004; ISBN: 0596007388).

Author Info:
By: O'Reilly Media
Rating: 4 stars4 stars4 stars4 stars4 stars / 25
May 26, 2005
TABLE OF CONTENTS:
  1. · Generics of Java 1.5 Tiger
  2. · Using Type-Safe Maps
  3. · Iterating Over Parameterized Types
  4. · Accepting Parameterized Types as Arguments
  5. · Returning Parameterized Types
  6. · Checking for Lint
  7. · Generics and Type Conversions
  8. · Using Type Wildcards
  9. · Writing Generic Types
  10. · Restricting Type Parameters

print this article
SEARCH DEVARTICLES

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.


blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- 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 ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials