C++中有,template<class T>
Java中怎么实现的,我看到有Interface Comparator<T>算是模板吗?

解决方案 »

  1.   

    java1.5增加了泛型的支持,形式上和C++的模板类似
    但是本质上是不一样的.
      

  2.   

    看JDK 5.0,在泛性机制内有类似C++的Template
      

  3.   

    public class TemplateClass {}/*
    Java 2, v5.0 (Tiger) New Features
    by Herbert Schildt
    ISBN: 0072258543
    Publisher: McGraw-Hill/Osborne, 2004
    */// Here, T is a type parameter that will be replaced by a real type 
    // when an object of type Gen is created. 
    class Gen<T> { 
      T ob; // declare an object of type T 
      // Pass the constructor a reference to  
      // an object of type T. 
      Gen(T o) { 
        ob = o; 
      } 
      // Return ob. 
      T getob() { 
        return ob; 
      } 
      // Show type of T. 
      void showType() { 
        System.out.println("Type of T is " + 
                           ob.getClass().getName()); 
      } 

    //Demonstrate the generic class. 
    public class GenDemo { 
      public static void main(String args[]) { 
        // Create a Gen reference for Integers.  
        Gen<Integer> iOb;  
        // Create a Gen<Integer> object and assign its 
        // reference to iOb.  Notice the use of autoboxing  
        // to encapsulate the value 88 within an Integer object. 
        iOb = new Gen<Integer>(88); 
        // Show the type of data used by iOb. 
        iOb.showType(); 
        // Get the value of in iOb. Notice that 
        // no cast is needed. 
        int v = iOb.getob(); 
        System.out.println("value: " + v); 
        System.out.println(); 
        // Create a Gen object for Strings. 
        Gen<String> strOb = new Gen<String>("Generics Test"); 
        // Show the type of data used by strOb. 
        strOb.showType(); 
        // Get the value of strOb. Again, notice 
        // that no cast is needed. 
        String str = strOb.getob(); 
        System.out.println("value: " + str); 
      } 
    }