2010-01-15 20 views
4

在C++中,我可以編寫一個模板函數,它接受充當參數的數據類型,以便單個函數可以在數據類型上重用。有沒有在Java中做類似的事情的規定?Java中的Mmimic C++模板函數

感謝,
羅傑

+0

正如答案所述,Java中的泛型是您所需要的。檢查這個線程在SO比較模板和泛型:http://stackoverflow.com/questions/36347/what-are-the-differences-between-generic-types-in-c-and-java – sateesh 2010-01-15 12:06:53

+1

他沒有問泛型。他問的是與此相當的java:http://www.sgi.com/tech/stl/functors.html – Jherico 2010-01-15 18:33:11

回答

2

不,Java沒有功能,但可以創建通用方法。看here

<T> void foo(T object) { 
/** there is your code */ 
} 
+0

Java沒有功能?當然你的意思是別的。 ;) – jalf 2010-01-15 14:31:43

+0

好的,給我看一些功能。我只知道方法,沒有功能,因爲Java中的所有東西都必須是類的一部分。你可以教我。 – Gaim 2010-01-15 15:17:23

+3

功能,方法...土豆,馬鈴薯... – Asaph 2010-01-15 15:34:49

2
 
Generics are a facility of generic programming that was added to the Java
programming language in 2004 as part of J2SE 5.0. They allow "a type or method
to operate on objects of various types while providing compile-time type safety.

周守軍wikipedia

3

這個人不是在問泛型。他詢問在<algorithm>中指定的那種模板函數。最接近Java的可能是爲每個要調用的函數類型定義(通用化)接口,然後將接受實例接口實例的自己的實用程序庫作爲輸入。例如,你可以創建以下接口

public interface UnaryOperator<T> { 
    public boolean test(T item); 
} 

,然後創建一個實用工具類,像這樣

public class Algorithms { 
    public static <T> void removeIf(Collection<T> c, UnaryOperator<T> op) { 
     Iterator<T> itr; 
     for (itr = c.iterator(); itr.hasNext();) { 
      T item = itr.next(); 
      if (op.test(item)) { 
       itr.remove(); 
      } 
     } 
    } 
} 

實際上,你可以找到在Apache Commons Collections中圖書館這種模式,但它的不靈活或廣泛的C++算法庫。我想給出STL函子和算法庫的任何特定的例子,你可以用Java編寫類似的東西,但沒有內建的我知道的等價物。我認識的大多數人(甚至C++開發人員)都認爲<algorithm>非常神祕。