List<String> animalList = List.of("Dog", "Cat", "Duck");
Set<String> animalSet = Set.of("Dog", "Cat", "Duck");
Map<Integer, String> animalMap = Map.of(1, "Dog", 2, "Cat", 3, "Duck");
Map<Integer, String> animalMap = Map.ofEntries(entry(1,"Dog"), entry(2,"Cat"), entry(3,"Duck"));
왜 UnsupportedOperationException이 터지는지 알아보자.
ImmutableCollections.java
class ImmutableCollections {
...
@jdk.internal.ValueBased
static abstract class AbstractImmutableCollection<E> extends AbstractCollection<E> {
// all mutating methods throw UnsupportedOperationException
@Override public boolean add(E e) { throw uoe(); }
@Override public boolean addAll(Collection<? extends E> c) { throw uoe(); }
@Override public void clear() { throw uoe(); }
@Override public boolean remove(Object o) { throw uoe(); }
@Override public boolean removeAll(Collection<?> c) { throw uoe(); }
@Override public boolean removeIf(Predicate<? super E> filter) { throw uoe(); }
@Override public boolean retainAll(Collection<?> c) { throw uoe(); }
}
...
@jdk.internal.ValueBased
static abstract class AbstractImmutableList<E> extends AbstractImmutableCollection<E>
implements List<E>, RandomAccess {
}
...
@jdk.internal.ValueBased
static abstract class AbstractImmutableSet<E> extends AbstractImmutableCollection<E>
implements Set<E> {
}
@jdk.internal.ValueBased
abstract static class AbstractImmutableMap<K,V> extends AbstractMap<K,V> implements Serializable {
}
}
UnsupportedOperationException
을 던지고 있다.put()
과 같은 연산을 하면 UnsupportedOperationException
을 던진다.ImmutableCollections.java
class ImmutableCollections {
@jdk.internal.ValueBased
static final class Set12<E> extends AbstractImmutableSet<E>
implements Serializable {
}
Set.java
public interface Set<E> extends Collection<E> {
@SuppressWarnings("unchecked")
static <E> Set<E> of() {
return (Set<E>) ImmutableCollections.EMPTY_SET;
}
static <E> Set<E> of(E e1) {
return new ImmutableCollections.Set12<>(e1);
}
}
참고
Java9의 불변 컬렉션 생성