반응형

"Arrays.asList" 를 이용해 만든 List 객체에 add 나 addAll 을 하는경우 오류가 발생합니다.

 

 

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractList.add(Unknown Source)
	at java.util.AbstractList.add(Unknown Source)
	at java.util.AbstractCollection.addAll(Unknown Source)

 

그 이유는 아래 asList 문서에 나와 있는데요. "Return a fixed-size list ..." 고정된 크기의 List 객체를 반환하기 때문에 add 같이 크기를 변경하는 함수 사용시 오류가 발생하게 됩니다.

Open Declaration   <String> List<String> java.util.Arrays.asList(String... a)

@SafeVarargs

asList
@SafeVarargs
public static <T> List<T> asList(T... a)

Returns a fixed-size list backed by the specified array. (Changes tothe returned list "write through" to the array.) This method actsas bridge between array-based and collection-based APIs, incombination with Collection.toArray(). The returned list isserializable and implements RandomAccess. 
This method also provides a convenient way to create a fixed-sizelist initialized to contain several elements: 
     List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
 
Type Parameters:T - the class of the objects in the arrayParameters:a - the array by which the list will be backedReturns:a list view of the specified array
반응형

'java' 카테고리의 다른 글

자신만의 properties 를 java 에서 사용하는 방법입니다.  (0) 2020.08.16
java - FormatUtil.java  (0) 2020.08.15
java - RequestUtil.java  (0) 2020.08.15
java - JsonUtil  (0) 2020.08.15
Java - JGit  (0) 2020.08.15
java snippet - base64, sha-256, sha-512  (0) 2020.08.10
java snippet - file util  (0) 2020.08.10
java snippet - SFTP  (2) 2020.07.29

+ Recent posts