티스토리 뷰



읽기전용으로 List를 생성함. List에 modify 가 일어나면 UnsupportedOperationException 이 발생


List<?> list = new anyList<>(); // any list (ArrayList, LinkedList other..)


list.add(any);


List<?> readOnlyList = java.util.Collections.unmodifiableList(list);


readOnlyList.get(index); // OK


readOnlyList.set(index, any); // throw UnsupportedOperationException


readOnlyList.add(any); // throw UnsupportedOperationException


readOnlyList.remove(any); // throw UnsupportedOperationException


readOnlyList.addAll(any); // throw UnsupportedOperationException


readOnlyList.remove(any); // throw UnsupportedOperationException


readOnlyList.clear(); // throw UnsupportedOperationException


List<?> readOnlySubLIst = readOnlyList.subList(fromIndex, toIndex); // Read only sublist


마찬가지로, java.util.Collections 의 함수를 이용하여 읽기전용 Set, 일기전용 Map을 생성할 수 있다.

Set<?> readOnlySet = java.util.Collections.unmodifiableSet(any set);

Map<key, ?> readOnlyMap = java.util.Collections.unmodifiableMap(any map);



[작성] devbible.tistory.com


댓글