Java Language
コレクションファクトリメソッド
サーチ…
前書き
Java 9の登場により、JavaのCollections APIに多くの新機能がもたらされます。その1つはコレクションファクトリメソッドです。これらのメソッドを使用すると、空でも空でも、 不変のコレクションを簡単に初期化できます。
これらのファクトリメソッドは、 List<E> 、 Set<E> 、およびMap<K, V>の各インタフェースでのみ使用できます。
構文
-
static <E> List<E> of() -
static <E> List<E> of(E e1) -
static <E> List<E> of(E e1, E e2) -
static <E> List<E> of(E e1, E e2, ..., E e9, E e10) -
static <E> List<E> of(E... elements) -
static <E> Set<E> of() -
static <E> Set<E> of(E e1) -
static <E> Set<E> of(E e1, E e2) -
static <E> Set<E> of(E e1, E e2, ..., E e9, E e10) -
static <E> Set<E> of(E... elements) -
static <K,V> Map<K,V> of() -
static <K,V> Map<K,V> of(K k1, V v1) -
static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2) -
static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, ..., K k9, V v9, K k10, V v10) -
static <K,V> Map<K,V> ofEntries(Map.Entry<? extends K,? extends V>... entries)
パラメーター
| メソッドw /パラメータ | 説明 |
|---|---|
List.of(E e) | クラスまたはインタフェースになることができるジェネリック型。 |
Set.of(E e) | クラスまたはインタフェースになることができるジェネリック型。 |
Map.of(K k, V v) | それぞれがクラスまたはインタフェースになることができるジェネリック型のキーと値のペア。 |
Map.of(Map.Entry<? extends K, ? extends V> entry) | そのキーがKかその子のいずれかであり、その値がVかその子であるMap.Entryインスタンス。 |
リストファクトリメソッドの例
-
List<Integer> immutableEmptyList = List.of();- 空の不変な
List<Integer>初期化します。
- 空の不変な
-
List<Integer> immutableList = List.of(1, 2, 3, 4, 5);- 不変の
List<Integer>を5つの初期要素で初期化します。
- 不変の
-
List<Integer> mutableList = new ArrayList<>(immutableList);- 変更可能な初期化
List<Integer>不変のList<Integer>。
- 変更可能な初期化
セットファクトリメソッドの例
-
Set<Integer> immutableEmptySet = Set.of();- 空の不変
Set<Integer>初期化します。
- 空の不変
-
Set<Integer> immutableSet = Set.of(1, 2, 3, 4, 5);- 5つの初期要素で不変の
Set<Integer>を初期化します。
- 5つの初期要素で不変の
-
Set<Integer> mutableSet = new HashSet<>(immutableSet);-
Set<Integer>不変のSet<Integer>から変更可能なSet<Integer>初期化します。
-
地図ファクトリメソッドの例
-
Map<Integer, Integer> immutableEmptyMap = Map.of();- 空の不変の
Map<Integer, Integer>初期化します。
- 空の不変の
-
Map<Integer, Integer> immutableMap = Map.of(1, 2, 3, 4);- 2つの初期キー値エントリを使用して不変の
Map<Integer, Integer>を初期化します。
- 2つの初期キー値エントリを使用して不変の
-
Map<Integer, Integer> immutableMap = Map.ofEntries(Map.entry(1, 2), Map.entry(3, 4));- 2つの初期キー値エントリを使用して不変の
Map<Integer, Integer>を初期化します。
- 2つの初期キー値エントリを使用して不変の
-
Map<Integer, Integer> mutableMap = new HashMap<>(immutableMap);- 不変の
Map<Integer, Integer>から変更可能なMap<Integer, Integer>を初期化します。
- 不変の
Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow