diff --git a/docs/CH12.md b/docs/CH12.md index 8dbf433..250310c 100644 --- a/docs/CH12.md +++ b/docs/CH12.md @@ -509,9 +509,34 @@ public class ConcreteFoo implements IFoo { 到這個章節為止,Java 的語法大部份已經說明完畢了,接下來要進行的,是讓您開始熟悉 J2SE 中一些常用的 API 類別,熟悉這些 API 類別是學習 Java 的必要過程,首先要先瞭解的是相關的物件容器(Container),像是 List、Map、Set 等,幾乎在各種應用領域中,都會很常使用到這些物件容器。 +## 12.4 自己的補充 +Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors. +泛型方法是一種有自己的類型參數的方法,這有點像泛型類型的宣告,但類型參數的範圍被限制在方法內,靜態或非靜態都是被允許的,甚到是類型的建構子也可以。 +The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method's return type. For static generic methods, the type parameter section must appear before the method's return type. +泛型方法的語法帶有一個類型參數,置於方法返回類型之前;對靜態的泛型方法,類型參數部分必須出現方法的返回類型之前。 +The Util class includes a generic method, compare, which compares two Pair objects: +在Util類別內有一個泛型方法,用以比較一對物件。可以看到static 後接角括號用以宣告在方法內的類型參數的泛型,然後方法的類型參數才需要將類型參數及其泛型寫上。返回值是布林類型。 +```java +public class Util { + public static boolean compare(Pair p1, Pair p2) { + return p1.getKey().equals(p2.getKey()) && + p1.getValue().equals(p2.getValue()); + } +} +``` +泛型pair ,角括號宣告了二個泛型,作為泛型類別的屬性。 + +```java +public class Pair { + + private K key; + private V value; +... +} +```