Home > Java > javaTutorial > body text

How to make elements of an array immutable in Java?

WBOY
Release: 2023-08-19 22:09:31
forward
866 people have browsed it

How to make elements of an array immutable in Java?

No, you cannot make the elements of an array immutable.

However, the unmodifiableList() method of the java.util.Collections class accepts an object of the List interface (an object that implements the class) and returns the unmodifiableList of the given object. Modify the form. Users have read-only access to the obtained list.

ArrayListThe asList() method accepts an array and returns a List object.

So, to convert an array to immutable -

  • Get the desired array.

  • Use the asList() method to convert it to a list object.

  • Pass the obtained list as a parameter to the unmodifiableList() method.

Example

Demonstration

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class UnmodifiableExample {
   public static void main(String args[]) {
      //Creating a string array
      String strArray[] = {"Raju", "Rama", "Rahman", "Rachel", "Ranbhir", "Rangan"};
      //Converting the string array to list object
      List<String> list = Arrays.asList(strArray);
      //Converting the List object to immutable
      List<String> immutable = Collections.unmodifiableList(list); System.out.println(immutable);
      immutable.add("komala");
   }
}
Copy after login

Output

[Raju, Rama, Rahman, Rachel, Ranbhir, Rangan]
Exception in thread "main" java.lang.UnsupportedOperationException
   at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
   at September19.UnmodifiableExample.main(UnmodifiableExample.java:19)
Copy after login

The above is the detailed content of How to make elements of an array immutable in Java?. 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