How to create unmodifiable (read-only) set in Java

1 Answer

0 votes
import java.util.Set;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Collections;

public class MyClass
{
    public static void main(String[] args)
    {
        Set<String> mutableSet = new HashSet<>(Arrays.asList("Java", "C", "C++", "Rust"));
 
        Set<String> unmodifiableSet = Collections.unmodifiableSet(mutableSet);
 
        try {
            unmodifiableSet.add("Python");
        }
        catch (UnsupportedOperationException e) {
            System.out.println("Exception: " + e);
        }
 
        System.out.println(mutableSet);     
        System.out.println(unmodifiableSet);
    }
}



/*
run:

Exception: java.lang.UnsupportedOperationException
[Java, C++, C, Rust]
[Java, C++, C, Rust]

*/

 



answered Mar 19, 2023 by avibootz

Related questions

1 answer 125 views
1 answer 411 views
1 answer 172 views
172 views asked Jun 28, 2020 by avibootz
1 answer 165 views
165 views asked Nov 19, 2016 by avibootz
1 answer 158 views
1 answer 224 views
...