java : Arrays.asList() + java.lang.UnsupportedOperationException
목차
- List 일반적인 생성 방법
- Arrays.asList 사용하여 생성 방법
- Arrays.asList 사용 시 문제를 해결방법
개요
Arrays.asList로 배열을 List로 선언 후 리스트 값이 추가되거나 제거 될때
UnsupportedOperationException
예외가 발생.
상세
1. List 일반적인 생성 방법
@Test
public void generalCreateList() {
List<String> sourceList = new ArrayList<>();
sourceList.add("order");
sourceList.add("delivery");
sourceList.add("claim");
sourceList.add("return");
sourceList.stream().forEach(System.out::println);
Assertions.assertFalse(sourceList.isEmpty());
}
2. Arrays.asList 사용하여 생성 방법
1번의 경우 소스 코드 라인 수가 길어져 2번과 같은 방법을 선호함.
하지만 Arrays.asList로 배열을 List로 선언 후 리스트 값이 추가되거나 제거 될때
UnsupportedOperationException
예외가 발생.
@Test
public void throwUnsupportedOperationExceptionTest() {
List<String> sourceList = Arrays.asList("order", "delivery", "claim", "return");
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
sourceList.add("cancel");
});
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
sourceList.remove(0);
});
}
Arrays.asList(..) is collection that can’t be expanded or shrunk (because it is backed by the original array, and it can’t be resized).
If you want to remove elements either create a new ArrayList(Arrays.asList(..) or remove elements directly from the array (that will be less efficient and harder to write)
결론 : Arrays.asList(..)는 리스트 길이를 고정시키기 때문에 추가하거나 제거할수 없음.
3. 2번 문제를 해결하기 위해 List 객체를 생성하고 인자로 넣어 사용
@Test
public void notThrowUnsupportedOperationExceptionTest() {
List<String> sourceList = new ArrayList<>(Arrays.asList("order", "delivery", "claim", "return"));
sourceList.add("cancel");
sourceList.stream().forEach(System.out::println);
Assertions.assertEquals(5, sourceList.size());
}
참고
https://stackoverflow.com/questions/7885573/remove-on-list-created-by-arrays-aslist-throws-unsupportedoperationexception
https://jistol.github.io/java/2017/07/21/caution-make-list/