Java Basics - Immutable Collections

1. What is an immutable collection?

  • A collection that cannot be modified.
  • The data items of the collection are provided at the time of creation, and cannot be changed throughout the life cycle, otherwise an error will be reported.

2. Why create immutable collections?

  • If some data cannot be modified, it is good practice to defensively copy it into an immutable collection.
  • Or the immutable form is safe when the collection object is called untrusted.

3. How to create an immutable collection?

  • In the List, Set, and Map interfaces, there is an of method, which can create an immutable collection.
method name illustrate
static <E> List<E> of(E...elements) Create a List collection object with the specified elements
static <E> Set<E> of(E...elements) Creates a Set collection object with the specified elements
static <K,V> Map<K,V> of(E...elements) Create a Map collection object with the specified elements

Guess you like

Origin blog.csdn.net/weixin_61275790/article/details/130064449