Home> Java> javaTutorial> body text

How do we create an immutable Set in Java 9?

王林
Release: 2023-08-20 17:57:28
forward
1334 people have browsed it

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

Immutable static factory methodSet.of()Can provide a convenient way to createimmutable collections in Java 9.

The set instance created using theSet.of()method has the following characteristics.

  • Collections returned by factory methods are usuallyimmutable. This means thatcannot add,removeorreplaceelements to the collection. Calling anymodifiermethod on a collection will throw anUnsupportedOperationException.
  • If the elements in the collection aremutable, it may cause the contents of the collection to appear to change.
  • You can createimmutable collectionsusing static factory methods that do not allownullelements. If you try to create a collection with null elements,NullPointerExceptionwill be thrown.
  • When creating an immutable collection,duplicate elementswill be rejected. Passing duplicate elements to a static factory method results in anIllegalArgumentException.
  • The iteration order of collection elements isunspecifiedand may change. The Chinese translation of

Grammar

Set.of(E... elements)
Copy after login

Example

is:

Example

import java.util.Set; public class SetOfMethodTest { public static void main(String args[]) { Set names = Set.of("Adithya", "Bhavish", "Chaitanya", "Jai"); System.out.println("Names - " + names); names.add("Raja"); // throws UnsupportedOperationException } }
Copy after login

Output

Names - [Bhavish, Adithya, Jai, Chaitanya] Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.ImmutableCollections.uoe(Unknown Source) at java.base/java.util.ImmutableCollections$AbstractImmutableSet.add(Unknown Source) at SetOfMethodTest.main(SetOfMethodTest.java:8)
Copy after login

The above is the detailed content of How do we create an immutable Set in Java 9?. 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!