Java
  Home arrow Java arrow Page 3 - Wildcards, Arrays, and Generics in Java
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  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
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

Wildcards, Arrays, and Generics in Java
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 5
    2007-06-07

    Table of Contents:
  • Wildcards, Arrays, and Generics in Java
  • Wildcard Types Versus Generic Methods
  • Using Array Types
  • Case Study: The Enum Class
  • Case Study: The sort() Method

  • 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


    Wildcards, Arrays, and Generics in Java - Using Array Types


    (Page 3 of 5 )

    Now, since we just said that Java won't let you make any of these arrays, you'd expect that would be pretty much the end of the story. But no! Even though we don't have real array implementations that perform the needed runtime behavior, Java allows us to declare the array type anyway. The catch is that you have to break type safety to use them by using an array of the raw type as their implementation:

      Trap<Mouse> [] tma = new Trap[10]; // unchecked warning
      Trap<Mouse> tm = new Trap<Mouse>();
      tma[0] = tm;
      Trap<Mouse> again = tma[0];

    Here, we declared an array of a generic type, Trap<Mouse>. Assigning any value (other than null) to the variable tma results in an unchecked warning from the compiler at the point of the assignment.

    What we are effectively telling the compiler here is to trust us to make sure that the array contains only the correct generic types and asking it to allow us to use it thereafter as if it were checked. We do not get warnings at each usage as we would with a raw type, only at the point where we assign the array. The catch is that the compiler can't prevent us from abusing the array. The unchecked warning at the point where we assign the array is just a representative warning that reminds us that it's possible to abuse the array later.

    What Good Are Arrays of Generic Types?

    Why does Java let us even declare arrays of generic types? One important usage is that it allows generic types to be used in variable-length argument methods. For example:

      void useLists( List<String> ... lists ) {
              List<String> ls0 = lists[0];
      }

    Another answer is that it's an escape hatch to preserve our ability to use arrays when necessary. You might want to do this for at least two reasons. First, arrays are faster than collections in many cases. The Java runtime is very good at optimizing array access and sometimes it just might be worth it to you to eat the compiler warning to get the benefits. Second, there is the issue of interfacing generic code to legacy code in which only the Javadoc and your faith in the developer are your guarantees as to the contents. By assigning raw arrays to generic instantiations, we can at least ensure that in simple usage we don't abuse the types in the new code.

    Wildcards in Array Types

    In general, wildcard instantiations of generics can be used as the base type for arrays in the same way that concrete instantiations can. Let's look at an example:

      ArrayList<?>[] arrayOfArrayLists = ...;

    This type declaration is an array of unbounded wildcard instantiations of ArrayList. Each element of the array can hold an instance of the wildcard type, meaning in this case, that each element of the array could hold a different instantiation of ArrayList. For example:

      arrayOfArrayLists[0] = new ArrayList<Date>();
      arrayOfArrayLists[1] = new ArrayList<String>();

    There is also a secret surprise we are going to spring on you relating to wildcard types in arrays. Although we said that Java won't let us create arrays of generic types, there is an exception to the rule. Java does allow us to create arrays of unbounded wildcard instantiations. Here are two examples:

      ArrayList<?>[] arrayOfArrayLists = new ArrayList<?>[10];
      arrayOfArrayLists[0] = new ArrayList<Date>();

      Trap<?> [] arrayOfTraps = new
    Trap<?>[10];
      arrayOfTraps[0] = new Trap<Mouse>();

    Here, we not only declared two arrays of wildcard instantiations, but we allocated the arrays as well! The trick is that the arrays must be of the unbounded wildcard type. Why does this work? Because each element in the unbounded wildcard instantiation of the array can hold any instantiation, no runtime check of the generic portion of the type is necessary at runtime. Any instantiation of ArrayList is assignable to the
    element of type ArrayList<?>, so only the check of the raw type is required.

    The term reifiable type is used to refer to any type that is unchanged by erasure. This includes plain Java concrete types, primitives, and unbounded wildcard instantiations. Reifiable types are kind of like the real people in The Matrix: they still exist when unplugged from the simulation.

    More Java Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "Learning Java, third edition," published...
     

    Buy this book now. This article was excerpted from chapter eight of the book Learning Java, third edition, written by Patrick Niemeyer and Jonathan Knudsen (O'Reilly; ISBN: 0596008732). Check it out today 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-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    Stay green...Green IT