Java/Generics/Generic Class

Материал из Java эксперт
Версия от 10:27, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A nongeneric class can be the superclass of a generic subclass.

   <source lang="java">

/* Java 2, v5.0 (Tiger) New Features by Herbert Schildt ISBN: 0072258543 Publisher: McGraw-Hill/Osborne, 2004

  • /

// A nongeneric class. class NonGen {

 int num; 

 NonGen(int i) { 
   num = i; 
 } 

 int getnum() { 
   return num; 
 } 

}

// A generic subclass. class Gen<T> extends NonGen {

 T ob; // declare an object of type T  
   
 // Pass the constructor a reference to   
 // an object of type T.  
 Gen(T o, int i) {  
   super(i); 
   ob = o;  
 }  
 
 // Return ob.  
 T getob() {  
   return ob;  
 }  

}

// Create a Gen object. public class HierDemo2 {

 public static void main(String args[]) {  
   
   // Create a Gen object for String. 
   Gen<String> w = new Gen<String>("Hello", 47); 
   
   System.out.print(w.getob() + " "); 
   System.out.println(w.getnum()); 
 }  

}


 </source>
   
  
 
  



A simple generic class.

   <source lang="java">

class Gen<T> {

 T ob; // declare an object of type T
 Gen(T o) {
   ob = o;
 }
 T getob() {
   return ob;
 }
 void showType() {
   System.out.println("Type of T is " + ob.getClass().getName());
 }

} public class GenDemo {

 public static void main(String args[]) {
   Gen<Integer> iOb;
   iOb = new Gen<Integer>(88);
   iOb.showType();
   int v = iOb.getob();
   System.out.println("value: " + v);
   System.out.println();
   Gen<String> strOb = new Gen<String>("Generics Test");
   strOb.showType();
   String str = strOb.getob();
   System.out.println("value: " + str);
 }

}


 </source>
   
  
 
  



A simple generic class hierarchy.

   <source lang="java">

/* Java 2, v5.0 (Tiger) New Features by Herbert Schildt ISBN: 0072258543 Publisher: McGraw-Hill/Osborne, 2004

  • /

class Gen<T> {

 T ob; 
   
 Gen(T o) {  
   ob = o;  
 }  
 
 // Return ob.  
 T getob() {  
   return ob;  
 }  

}

// A subclass of Gen that defines a second // type parameter, called V. class Gen2<T, V> extends Gen<T> {

 V ob2; 

 Gen2(T o, V o2) { 
   super(o); 
   ob2 = o2; 
 } 

 V getob2() { 
   return ob2; 
 } 

}

// Create an object of type Gen2. public class HierDemo {

 public static void main(String args[]) {  
   
   // Create a Gen2 object for String and Integer. 
   Gen2<String, Integer> x = 
     new Gen2<String, Integer>("Value is: ", 99);  

   System.out.print(x.getob()); 
   System.out.println(x.getob2()); 
 }  

}


 </source>
   
  
 
  



Custom Generic Object Tester

   <source lang="java">

/* License for Java 1.5 "Tiger": A Developer"s Notebook

    (O"Reilly) example package

Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) by Brett McLaughlin and David Flanagan. ISBN: 0-596-00738-8 You can use the examples and the source code any way you want, but please include a reference to where it comes from if you use it in your own products or services. Also note that this software is provided by the author "as is", with no expressed or implied warranties. In no event shall the author be liable for any direct or indirect damages arising in any way out of the use of this software.

  • /

import java.io.IOException; import java.io.PrintStream;

import java.util.LinkedList; import java.util.List; class GuitarManufacturerList extends LinkedList<String> {

 public GuitarManufacturerList() {
   super();
 }
 public boolean add(String manufacturer) {
   if (manufacturer.indexOf("Guitars") == -1) {
     return false;
   } else {
     super.add(manufacturer);
     return true;
   }
 }

} public class CustomObjectTester {

 /** A custom object that extends List */
 private GuitarManufacturerList manufacturers;
 public CustomObjectTester() {
   this.manufacturers = new GuitarManufacturerList();
 }
 /**
*

Test iterating over an object that extends List

  */
 public void testListExtension(PrintStream out) throws IOException {
   // Add some items for good measure
   manufacturers.add("Epiphone Guitars");
   manufacturers.add("Gibson Guitars");
   // Iterate with for/in
   for (String manufacturer : manufacturers) {
     out.println(manufacturer);
   }
 }
 public static void main(String[] args) {
   try {
     CustomObjectTester tester = new CustomObjectTester();
     tester.testListExtension(System.out);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }

}


 </source>
   
  
 
  



Demonstrate the non generic class

   <source lang="java">

class NonGen {

 Object ob; 
   
 NonGen(Object o) {  
   ob = o;  
 }  
 
 Object getob() {  
   return ob;  
 }  
 void showType() {  
   System.out.println("Type of ob is " +  
                      ob.getClass().getName());  
 }  

}


public class NonGenDemo {

 public static void main(String args[]) {  
   NonGen integerObject;   
   integerObject = new NonGen(88);  
 
   integerObject.showType(); 

   int v = (Integer) integerObject.getob();  
   System.out.println("value: " + v);  
 

   NonGen strOb = new NonGen("Non-Generics Test");  
   strOb.showType(); 

   String str = (String) strOb.getob();  
   System.out.println("value: " + str);  

   integerObject = strOb; 
   v = (Integer) integerObject.getob(); 
 }  

}


 </source>
   
  
 
  



Java hierarchy generic class

   <source lang="java">

/* Java 2, v5.0 (Tiger) New Features by Herbert Schildt ISBN: 0072258543 Publisher: McGraw-Hill/Osborne, 2004

  • /

// Here, T is bound by Object by default. class Gen<T> {

 T ob; // here, T will be replaced by Object 
   
 Gen(T o) {  
   ob = o;  
 }  
 
 // Return ob.  
 T getob() {  
   return ob;  
 }  

}

// Here, T is bound by String. class GenStr<T extends String> {

 T str; // here, T will be replaced by String 

 GenStr(T o) {  
   str = o;  
 }  

 T getstr() { return str; } 

} public class GenTypeDemo {

 public static void main(String args[]) {  
   Gen<Integer> iOb = new Gen<Integer>(99);  
   Gen<Float> fOb = new Gen<Float>(102.2F); 

   System.out.println(iOb.getClass().getName()); 
   System.out.println(fOb.getClass().getName()); 
 } 

}


 </source>
   
  
 
  



Pair of template arguments

   <source lang="java">

/* $Id$

*
* Behavior Protocols Tools - Parsers, Transformations
* Copyright (C) 2006-2007  DSRG, Charles University in Prague
*                          http://dsrg.mff.cuni.cz/
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*
*/

package org.ow2.dsrg.fm.bptools.util;

/**

* Keeps pair of values whose type is given by template arguments
* @author thorm
*/

public class Pair<T1, T2> {

   /**
    * Creates a new instance of Pair
    * @param first first value
    * @param second second value
    */
   public Pair(T1 first, T2 second) {
       this.first = first;
       this.second = second;
   }
   
   public boolean equals(Object obj) {
       if (obj instanceof Pair) {
           Pair other = (Pair)obj;
            return (other.first == null ? this.first == null : other.first.equals(this.first)) && 
                    (other.second == null ? this.second == null : other.second.equals(this.second));
       }
       else
           return false;
   }
   public String toString(){
       return first.toString() +"::"+second.toString() ;
   }
   
   /**
    * first value
    */
   public T1 first;
   /**
    * second value
    */
   public T2 second;

}

 </source>
   
  
 
  



Stats attempts (unsuccessfully) to create a generic class

   <source lang="java">

/* Java 2, v5.0 (Tiger) New Features by Herbert Schildt ISBN: 0072258543 Publisher: McGraw-Hill/Osborne, 2004

  • /

// Stats attempts (unsuccessfully) to create a generic class that can compute // the average of an array of numbers of any given type. // The class contains an error! public class Stats<T> {

 T[] nums; // nums is an array of type T 
   
 // Pass the constructor a reference to   
 // an array of type T. 
 Stats(T[] o) {  
   nums = o;  
 }  
 
 // Return type double in all cases. 
 double average() {  
   double sum = 0.0; 

   for(int i=0; i < nums.length; i++)  
     sum += nums[i].doubleValue(); // Error!!! 

   return sum / nums.length; 
 }  

}


 </source>
   
  
 
  



Use the instanceof operator with a generic class hierarchy.

   <source lang="java">

/* Java 2, v5.0 (Tiger) New Features by Herbert Schildt ISBN: 0072258543 Publisher: McGraw-Hill/Osborne, 2004

  • /

class Gen<T> {

 T ob;  
    
 Gen(T o) {   
   ob = o;   
 }   
  
 // Return ob.   
 T getob() {   
   return ob;   
 }   

}

// A subclass of Gen. class Gen2<T> extends Gen<T> {

 Gen2(T o) {  
   super(o);  
 }  

}

// Demonstrate runtime type ID implications of generic class hierarchy.  

public class HierDemo3 {

 public static void main(String args[]) {   
    
   // Create a Gen object for Integers.  
   Gen<Integer> iOb = new Gen<Integer>(88);  
 
   // Create a Gen2 object for Integers.  
   Gen2<Integer> iOb2 = new Gen2<Integer>(99);   
   
   // Create a Gen2 object for Strings.  
   Gen2<String> strOb2 = new Gen2<String>("Generics Test");   
 
   // See if iOb2 is some form of Gen2. 
   if(iOb2 instanceof Gen2<?>)   
     System.out.println("iOb2 is instance of Gen2");  

   // See if iOb2 is some form of Gen. 
   if(iOb2 instanceof Gen<?>)   
     System.out.println("iOb2 is instance of Gen");  
 
   System.out.println();  
 
   // See if strOb2 is a Gen2. 
   if(strOb2 instanceof Gen2<?>)   
     System.out.println("strOb is instance of Gen2");  
 
   // See if strOb2 is a Gen. 
   if(strOb2 instanceof Gen<?>)   
     System.out.println("strOb is instance of Gen");  

   System.out.println();  
 
   // See if iOb is an instance of Gen2, which its not. 
   if(iOb instanceof Gen2<?>)   
     System.out.println("iOb is instance of Gen2");  
 
   // See if iOb is an instance of Gen, which it is. 
   if(iOb instanceof Gen<?>)   
     System.out.println("iOb is instance of Gen");  
 
   // The following can"t be compiled because  
   // generic type info does not exist at runtime. 

// if(iOb2 instanceof Gen2<Integer>) // System.out.println("iOb2 is instance of Gen2<Integer>");

 }   

}


 </source>