Skip to content

Commit 24b94c4

Browse files
committed
泛型方法
1 parent 9d9bc73 commit 24b94c4

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

docs/CH12.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -517,8 +517,26 @@ Generic methods are methods that introduce their own type parameters. This is si
517517
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.
518518
泛型方法的語法帶有一個類型參數,置於方法返回類型之前;對靜態的泛型方法,類型參數部分必須出現方法的返回類型之前。
519519

520+
The Util class includes a generic method, compare, which compares two Pair objects:
521+
在Util類別內有一個泛型方法,用以比較一對物件。可以看到static 後接角括號用以宣告在方法內的類型參數的泛型,然後方法的類型參數才需要將類型參數及其泛型寫上。返回值是布林類型。
520522

523+
```java
524+
public class Util {
525+
public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {
526+
return p1.getKey().equals(p2.getKey()) &&
527+
p1.getValue().equals(p2.getValue());
528+
}
529+
}
530+
```
531+
泛型pair ,角括號宣告了二個泛型,作為泛型類別的屬性。
521532

533+
```java
534+
public class Pair<K, V> {
522535

536+
private K key;
537+
private V value;
538+
...
539+
}
540+
```
523541

524542

0 commit comments

Comments
 (0)