Java
  Home arrow Java arrow 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  
Actuate Whitepapers 
VeriSign Whitepapers 
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
     
    Iron Speed
     
    ADVERTISEMENT

    Generate data entry and reporting .NET Web apps in minutes, straight from your database. Read our FREE whitepaper “Build Web 2.0 Applications Without Hand-Coding” Download now!

    Generics of Java 1.5 Tiger


    (Page 1 of 10 )

    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).

    Without any further ado, I’m going to dive right into the deep end of the pool. More than any other feature, Tiger (or whatever version it ends up being labeled as) brings to the table generics. While the name might throw you, generics actually bring a greater degree of type safety to Java than anything you could imagine. It’s finally possible to create parameterized types, lists that only accept Strings, and ditch all that annoying class-casting code. Even better, you can limit types that your custom classes and methods accept, removing a huge amount of tedious error-checking and type-checking code.

    Additionally, generics are foundational to many of the other features specific to Tiger. Generics have a bearing on varargs, annotations, enumerations, collections, and even some of the new concurrency utilities of the language. While you may want to browse through other parts of this book, you’d do well to take your time and really work through this chapter, lab by lab. There, that’s enough introduction for a few chapters—let’s get to it.

    Using Type-Safe Lists 

    One of Java’s greatest strengths is its typing. Everything is an object, and, in fact, every class either explicitly or implicitly descends from Object. This provides a tremendous amount of type-safety—your methods can take Integers, Strings, Lists, Maps, or your own custom objects as parameters, and know at the outset what they’ll have to work with.

    With all this type-safety, Java has a gaping hole that Tiger finally fills— the ability to create type-safe arrays and lists, ensuring that collections of objects only allow for a certain type to be inserted.

          In this chapter:

    • Using Type-Safe Lists
    • Using Type-Safe Maps
    • Iterating Over
      Parameterized
      Types 
    • Accepting Parameterized
      Types as
      Arguments
    • Returning
      Parameterized
      Types
    •  Using Parameterized
      Types as Type Parameters
    • Checking for Lint
    • Generics and
      Type Conversions
    • Using TypeWildcards
    • Writing GenericTypes
    • Restricting Type Parameters

    How do I do that?

    One of the most annoying tasks in Java is having to cast objects pulled out of a List, when you already know what’s in the List (such as when you fill it yourself, or a trusted source handles populating it):

      List listOfStrings = getListOfStrings();
      for (Iterator i = listOfStrings.iterator(); i.hasNext(); ) {
      String item = (String)i.next();
      // Work with that string }

    Remove that cast, though—pull out (String)—and you’ll get a compiler error:

      [javac] Compiling 1 source file to code\classes
      [javac] code\src\com\oreilly\tiger\ch02\GenericsTester.java:17:
                incompatible types
      [javac] found : java.lang.Object
      [javac] required: java.lang.String
      [javac] String item = i.next();
      [javac]
      [javac] Note: code\src\com\oreilly\tiger\ch02\GenericsTester.java uses
                unchecked or unsafe operations.
      [javac] Note: Recompile with -Xlint:unchecked for details.
      [javac] 1 error

    This particular
    code sample is in
    com.oreilly.
    tiger.ch02.
    GenericsTester.

    No matter how much you trust the getListOfStrings() method, the compiler doesn’t trust it one bit. It assumes the worst, and if you’ve ever had anyone else work with you, you realize the compiler is often right more than you are.

    Generics let you finally get around this, by limiting the type that a particular List will accept:

      List<String> listOfStrings;

    Here, and in
    other output
    dumps, I’ve made
    slight formatting
    changes to fit
    things on the
    printed page.

    While this syntax probably looks pretty odd, it does the trick— listOfStrings can now only be populated with String instances. You also need to assign it an instance that only accepts the same type:

      List<String> listOfStrings = new LinkedList<String>();

    I realize that the syntax just gets weirder, but that’s what you have to work with. Angle brackets everywhere! Now you can add Strings to this List, but you cannot add any other type:

      List<String> onlyStrings = new LinkedList<String>();
      onlyStrings.add("Legal addition");
      onlyStrings.add(new StringBuilder("Illegal Addition"));
      onlyStrings.add(25);

    The compiler will let you know about the problem:

      [javac] code\src\com\oreilly\tiger\ch02\GenericsTester.java:24:
                  cannot find symbol
      [javac] symbol : method add(java.lang.StringBuilder)
      [javac] location: interface java.util.List<java.lang.String>
      [javac]    onlyStrings.add(new StringBuilder("Illegal Addition"));
      [javac]
      [javac] src\com\oreilly\tiger\ch02\GenericsTester.java:25: cannot find symbol
      [javac] symbol : method add(int)
      [javac] location: interface java.util.List<java.lang.String>
      [javac]     onlyStrings.add(25);
      [javac]
      [javac] Note: code\src\com\oreilly\tiger\ch02\GenericsTester.java uses
                  unchecked or unsafe operations.
      [javac] Note: Recompile with -Xlint:unchecked for details.
      [javac] 2 errors

    What just happened?

    In pre-Tiger versions of Java, the method signature for add() in List looked like this:

      public boolean add(Object obj);

    In Tiger, though, things have changed:

      public boolean add(E o);

    Before you go looking up E in Javadoc, though, it’s just a placeholder. It indicates that this method declares a type variable (E) and can be parameterized. The entire List class is generic:

      public interface List<E> extends Collection, Iterable {

    There’s that E again. When you supply a type in the initialization of a List, you parameterize the type—you indicate what type its parameters can accept:

      List<String> onlyStrings = new LinkedList<String>();

    One way to understand this is to imagine that the compiler replaces every occurrence of E with the type you supplied—in this case, a String. Of course, this is just done for this particular instance of List. You can have multiple Lists, all with different types, and all in the same program block.

    The end result of all this is that onlyStrings no longer has a method add(Object obj); it only has add(String o). So, when the compiler sees add() with anything other than a String parameter, it kicks out an error. This is the power of generics, and parameterized types—they provide built-in type safety for your collection types.

    What about...

    ...lists of primitive types? The types that are allowed by Lists (and other collection classes) are all objects; as a result, they don’t work with primitive values. The introduction of generics, despite all of its wonder and magic, doesn’t change this. So the following won’t compile:

      List<int> list = new LinkedList<int>();

    However, this will:

      List<Integer> list = new LinkedList<Integer>();

    If you’re thinking that now you’ve got to do all sorts of annoying conversion between int and Integer, that’s just because you haven’t made it to Chapter 4 yet. In that chapter, you’ll see that autoboxing makes this a particularly useful way to deal with primitives.

    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...

    Iron Speed

    Iron Speed





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