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

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

PHPz
PHPzforward
2023-08-20 11:49:171364browse

在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>

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>
   }
}

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>

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete