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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 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 140 views
140 views asked Nov 19, 2016 by avibootz
1 answer 171 views
1 answer 113 views
1 answer 316 views
1 answer 218 views
...