Home > Java > javaTutorial > body text

In Java 9, how can we create an immutable list?

PHPz
Release: 2023-08-20 11:49:17
forward
1373 people have browsed it

在Java 9中,我们如何创建一个不可修改的列表?

If after creating an unmodifiable list instance, you cannot add, remove or replace# from the list ## element, the list is considered an unmodifiable list. Static factory method: List.of() Provides a convenient way to create unmodifiable lists in Java 9.

The list instance created using the

List.of() method has the following characteristics.

    The list returned by the factory method is usually
  • immutable. This means that it is not possible to add, remove or replace elements from the list. Calling any modifier method on a list throws UnsupportedOperationException.
  • If the containing elements of the list are
  • variable, it may cause the contents of the list to change.
  • Immutable lists can be created using static factory methods that do not allow
  • null elements. If you try to create a list with null elements, NullPointerException will be thrown.
  • An unmodifiable list is
  • serializable if all elements are serializable.
  • The order of the elements in the list is the same as the order of the supplied arguments or the order of the elements in the supplied array. The Chinese translation of
Grammar

<strong>List.of(E... elements)</strong>
Copy after login

Example

is:

Example

import java.util.List;
public class UnmodifiedListTest {
   public static void main(String[] args) {
<strong>      List<String></strong> countries = <strong>List.of</strong>("India", "Australia", "England", "Newzealand");
      System.out.println("Countries - " + countries);
      countries.add("Srilanka"); <strong>// throws UnsupportedOperationException</strong>
   }
}
Copy after login

Output

<strong>Countries - [India, Australia, England, Newzealand]
Exception in thread "main" java.lang.UnsupportedOperationException
 at java.base/java.util.ImmutableCollections.uoe(Unknown Source)
 at java.base/java.util.ImmutableCollections$AbstractImmutableList.add(Unknown Source)
 at UnmodifiedListTest.main(UnmodifiedListTest.java:7)</strong>
Copy after login

The above is the detailed content of In Java 9, how can we create an immutable list?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template