Collections
List.of: 変更できない List を作る
List.of が返すコレクションは、変更操作を受け付けません。
SourceFixedLists.java
Java 21
package examples.list;
import java.util.List;
public final class FixedLists {
private FixedLists() {}
public static List<String> colors() {
return List.of("green", "blue");
}
}TestFixedListsTest.java
Java 21
package examples.list;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.List;
import org.junit.jupiter.api.Test;
class FixedListsTest {
@Test
void ListOfは指定した順序の要素を持つ() {
assertEquals(List.of("green", "blue"), FixedLists.colors());
}
@Test
void ListOfが返すListには要素を追加できない() {
var colors = FixedLists.colors();
assertThrows(UnsupportedOperationException.class, () -> colors.add("red"));
}
}01Assertion
このテストで確認できること
- List.of で指定した順序の要素を読める
- add を実行すると UnsupportedOperationException になる
List.of は不変の List を返します。要素を追加・削除する用途には ArrayList を使います。
OBSERVED RESULT
expected exception:
UnsupportedOperationException