Home  >  Article  >  Java  >  How to make elements of an array immutable in Java?

How to make elements of an array immutable in Java?

WBOY
WBOYforward
2023-08-19 22:09:31858browse

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");
   }
}

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)

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!

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