Java
  Home arrow Java arrow Page 4 - Wildcards and Generic Methods 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 and Generic Methods in Java
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 6
    2007-05-31

    Table of Contents:
  • Wildcards and Generic Methods in Java
  • Reading, Writing, and Arithmetic
  • Wildcard Type Relationships
  • Generic Methods
  • Type Inference from Arguments

  • 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 and Generic Methods in Java - Generic Methods


    (Page 4 of 5 )

    Thus far in this chapter, we've talked about generic types and the implementation of generic classes. Now, we're going to look at a different kind of generic animal: generic methods. Generic methods essentially do for individual methods what type parameters do for generic classes. But as we'll see, generic methods are smarter and can figure out their parameter types from their usage context, without having to be explicitly parameterized. (In reality, of course, it is the compiler that does this.) Generic methods can appear in any class (not just generic classes) and are very useful for a wide variety of applications.

    First, let's quickly review the way that we've seen regular methods interact with generic types. We've seen that generic classes can contain methods that use type variables in their arguments and return types in order to adapt themselves to the parameterization of the class. We've also mentioned that generic types themselves can be used in most of the places that any other type can be used. So methods of generic or nongeneric classes can use generic types as argument and return types as well. Here are examples of those usages:

      // Not generic methods

      class GenericClass< T > {
         
    // method using generic class parameter type
         
    public void T cache( T entry ) { ... }
      }
      class RegularClass {
         
    // method using concrete generic type
         
    public List<Date> sortDates( List<Date> dates ) { ... }
         
    // method using wildcard generic type
          public List<?> reverse( List<?> dates ) { ... }
      }

    The cache() method in GenericClass accepts an argument of the parameter type T and also returns a value of type T. The sortDates() method, which appears in the nongeneric example class, works with a concrete generic type, and the reverse() method works with a wildcard instantiation of a generic type. These are examples of methods that work with generics, but they are not true generic methods.

    Generic Methods Introduced

    Like generic classes, generic methods have a parameter type declaration using the <> syntax. This syntax appears before the return type of the method:

      // generic method
     
    <T> T cache( T entry ) { ... }

    This cache() method looks very much like our earlier example, except that it has its own parameter type declaration that defines the type variable T. This method is a generic method and can appear in either a generic or nongeneric class. The scope of T is limited to the method cache() and hides any definition of T in any enclosing generic class. As with generic classes, the type T can have bounds:

      <T extends Entry & Cacheable > T cache( T entry ) { ... }

    Unlike a generic class, it does not have to be instantiated with a specific parameter type for T before it is used. Instead, it infers the parameter type T from the type of its argument, entry. For example:

      BlogEntry newBlogEntry = ...;
      NewspaperEntry newNewspaperEntry = ...;

      BlogEntry oldEntry = cache( newBlogEntry );
      NewspaperEntry old = cache( newNewspaperEntry );

    Here, our generic method cache() inferred the type BlogEntry (which we'll presume for the sake of the example is a type of Entry and Cacheable). BlogEntry became the type T of the return type and may have been used elsewhere internally by the method. In the next case, the cache() method was used on a different type of Entry and was able to return the new type in exactly the same way. That's what's powerful about generic methods: the ability to infer a parameter type from their usage context. We'll go into detail about that next.

    Another difference with generic class components is that generic methods may be static:

      class MathUtils {
        
    public static <T extends Number> T max( T x, T y ) { ... }
      }

    Constructors for classes are essentially methods, too, and follow the same rules as generic methods, minus the return type.

    More Java Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "Learning Java, third edition," published...
       · // Not generic methods class GenericClass< T > { // method using generic...
     

    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 4 Hosted by Hostway
    Stay green...Green IT