Serie: Angelia
java
18 líneas
· Actualizado 2026-09-27
Pair.java
Angelia/Java/Week_6_7/code/06_generics_collections/Pair.java
/**
* 有兩個型別參數的泛型 record:Pair<A, B>。
*
* record 會自動產生建構子、存取器(first()、second())、equals、hashCode 與 toString,
* 是不可變(immutable)資料的最佳寫法——這也讓它成為安全的雜湊表鍵(見第 8 章)。
*/
public record Pair<A, B>(A first, B second) {
/** 泛型「靜態方法」:型別參數寫在回傳型別前面。 */
public static <A, B> Pair<A, B> of(A first, B second) {
return new Pair<>(first, second);
}
/** 交換前後:回傳一個新的 Pair<B, A>(record 是不可變的,所以不是「修改自己」)。 */
public Pair<B, A> swap() {
return new Pair<>(this.second, this.first);
}
}
Artículos relacionados
Angelia
haskell
EN
Actualizado 2026-02-03
Adding.hs
Adding.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Adding.hs).
Leer artículo →
Angelia
haskell
EN
Actualizado 2026-02-03
Area.hs
Area.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Area.hs).
Leer artículo →
Angelia
haskell
EN
Actualizado 2026-02-03
Chess.hs
Chess.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Chess.hs).
Leer artículo →
Angelia
haskell
EN
Actualizado 2026-02-03
ChessGraphics.hs
ChessGraphics.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/ChessGraphics.hs).
Leer artículo →
Angelia
haskell
EN
Actualizado 2026-02-03
Examples.hs
Examples.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Examples.hs).
Leer artículo →
Angelia
haskell
EN
Actualizado 2026-02-03
Fibonacci.hs
Fibonacci.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Fibonacci.hs).
Leer artículo →