23.6. Heap Sort

 
[Page 698 ( continued )]

21.4. Generic Methods

You can declare generic interfaces (e.g., the Comparable interface in Figure 21.1(b)) and classes (e.g., the GenericStack class in Listing 21.1). You can also use generic types to declare generic methods. For example, Listing 21.2 declares a generic method print (lines 10 “14) to print an array of objects. Line 6 passes an array of integer objects to invoke the generic print method. Line 7 invokes print with an array of strings.

Listing 21.2. GenericMethodDemo.java
 1   public class   GenericMethodDemo {  2   public static void   main(String[] args ) {  3     Integer[] integers = {   1   ,   2   ,   3   ,   4   ,   5   };  4     String[] strings = {   "London"   ,   "Paris"   ,   "New York"   ,   "Austin"   };  5  6     GenericMethodDemo.<Integer>print(integers);  7     GenericMethodDemo.<Integer>print(strings);  8  }  9 10   public static    <E>   void  print(  E  [] list) { 11   for   (   int   i =     ; i < list.length; i++) 12      System.out.print(list[i] +   " "   ); 13    System.out.println(); 14  } 15 } 

To invoke a generic method, prefix the method name with the actual type in angle brackets. For example,

 GenericMethodDemo.<Integer>print(integers); GenericMethodDemo.<String>print(strings); 

A generic type can be bounded. For example, Listing 21.3 revises the equalArea method in Listing 10.2, TestGeometricObject.java to test whether two geometric objects have the same area. The bounded generic type <E extends GeometricObject> (line 9) specifies that E is a generic subtype of GeometricObject . You must invoke equalArea by passing two instances of GeometricObject .


[Page 699]
Listing 21.3. BoundedTypeDemo.java
 1   public class   BoundedTypeDemo {  2   public static void   main(String[] args) {  3     Rectangle rectangle =   new   Rectangle(   2   ,   2   );  4     Circle9 circle =   new   Circle9(   2   );  5  6     System.out.println(   "Same area? "   +  7       BoundTypeDemo.<GeometricObject>equalArea(rectangle, circles);  8   }  9 10   public static    <E   extends   GeometricObject>   boolean  equalArea( 11  E  object1,  E  object2) { 12   return   object1.findArea() == object2.findArea(); 13   } 14 } 

Note

An unbounded generic type <E> is the same as <E extends Object> .


Note

To declare a generic type for a class, place the generic type after the class name, such as GenericStack<E> . To declare a generic type for a method, place the generic type before the method return type, such as <E> void max(E o1, E o2) .


 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net