Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,104 questions

40,777 answers

573 users

How to make ArrayList read only in Java

1 Answer

0 votes
import java.util.*;
  
public class MyClass {
    public static void main(String args[]) {
          
        ArrayList<String> al1 = new ArrayList<String>();  
        al1.add("java");
        al1.add("c++");
        al1.add("c#");
        al1.add("python");
        al1.add("javascript");
        al1.add("c");
        System.out.println(al1); 
   
        List<String> unmodifiableList= Collections.unmodifiableList(al1);  
    
        unmodifiableList.add("php"); // Error
    }
}
  
  
/*
run:
  
[java, c++, c#, python, javascript, c]

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1060)
	at MyClass.main(MyClass.java:17)
 
*/

 





answered Jun 28, 2020 by avibootz

Related questions

1 answer 82 views
82 views asked Nov 19, 2016 by avibootz
1 answer 22 views
1 answer 230 views
1 answer 100 views
...