Collections.emptyList()と。新しいリストインスタンス
1. 序章
この短いチュートリアルでは、 Collections.emptyList()と新しいリストインスタンスの違いを説明します。
2. 不変性
java.util.Collections.emptyList()と新しいリストの主な違い(例: new ArrayList <>() 不変性です。
Collections.emptyList()は、変更できないリスト( java .util.Collections.EmptyList )を返します。
新しいリストインスタンスを作成するときは、実装に応じて変更できます。
@Test
public void givenArrayList_whenAddingElement_addsNewElement() {
List<String> mutableList = new ArrayList<>();
mutableList.add("test");
assertEquals(mutableList.size(), 1);
assertEquals(mutableList.get(0), "test");
}
@Test(expected = UnsupportedOperationException.class)
public void givenCollectionsEmptyList_whenAdding_throwsException() {
List<String> immutableList = Collections.emptyList();
immutableList.add("test");
}
3. オブジェクトの作成
Collection.emptyList()は、ソースコードに示すように、新しい空のリストインスタンスを1回だけ作成します。
public static final List EMPTY_LIST = new EmptyList<>();
public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST;
}
4. 読みやすさ
空のリストを明示的に作成する場合は、 Collections.emptyList() 本来の意図をよりよく表現した例 new ArrayList <>() 。
5. 結論
ここでは、 Collections.emptyList()と新しいリストインスタンスの違いに焦点を当てました。
いつものように、完全なソースコードはGitHubで利用できます。