From 9d9bc737eba81632a0b8809d5d78e6bbb7f8961a Mon Sep 17 00:00:00 2001 From: gogobook Date: Sun, 6 Nov 2016 14:50:01 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E5=8A=A0=E5=85=A5=E6=B3=9B=E5=9E=8B?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/CH12.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/CH12.md b/docs/CH12.md index 8dbf433..8014dc1 100644 --- a/docs/CH12.md +++ b/docs/CH12.md @@ -509,6 +509,13 @@ 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. +泛型方法的語法帶有一個類型參數,置於方法返回類型之前;對靜態的泛型方法,類型參數部分必須出現方法的返回類型之前。 From 24b94c43996be623a088a851b255d27265ba68fa Mon Sep 17 00:00:00 2001 From: gogobook Date: Sun, 6 Nov 2016 15:04:32 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E6=B3=9B=E5=9E=8B=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/CH12.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/CH12.md b/docs/CH12.md index 8014dc1..250310c 100644 --- a/docs/CH12.md +++ b/docs/CH12.md @@ -517,8 +517,26 @@ Generic methods are methods that introduce their own type parameters. This is si 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; +... +} +```