개발
Java List UnsupportedOperationException / for문 리스트 삭제
juliea
2020. 5. 18. 13:41
728x90
String으로 받아온 문장을 [.] 단위로 split해서 ArrayList로 저장하는 과정에서공백이 있는 경우를 발견.
단순히 공백이 있는 경우 리스트에서 삭제를 하고 싶었으나,
Java List UnsupportedOperationException라는 에러가 발생해서 지울 수가 없었다.....
1. List를 만들 때 단지 Arrays.asList를 사용
출처의 하단의 케이스와 일치했기 때문에 new ArrayList를 추가하여 List를 만들어줬다.
2. fot문을 돌리면서 리스트를 삭제하니 또 에러가 발생
공백은 for문으로 리스트를 확인하면서 진행하고 싶었으나,
index를 붙여서 사용해도 마찬가지 였기때문에 알아보니,
Iterator라는 인터페이스를 이용하면 깔끔하게 지울 수 있었다.
변경후
//1. enter
String teststr = dDto.getContent().replaceAll("(\r|\n|\r\n|\n\r)", "");
//2. question mark and exclamation mark
teststr = teststr.replaceAll("[?]", ".");
teststr = teststr.replaceAll("[!]", ".");
//3. spilt depending on .
List<String> allCheckList = new ArrayList<>(Arrays.asList(teststr.split("[.]")));
List<String> checkList = new ArrayList<String>();
//4. remove blank
for(Iterator<String> it = allCheckList.iterator() ; it.hasNext() ; ) {
String value = it.next();
if(value.length()==0) {
it.remove();
}
출처 : https://www.baeldung.com/java-list-unsupported-operation-exception
728x90