

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create an unmodifiable map in Java?
Let us first create a Hashtable and set key-value pair −
Hashtable<String,String>hash = new Hashtable<String,String>(); hash.put("key1", "value1"); hash.put("key2", "value2"); hash.put("key3", "value3");
Now, create an unmodifiable map −
Map map = Collections.unmodifiableMap(hash);
If you will try to add a new key and value to the Map, then error will generate −
Exception in thread "main" java.lang.UnsupportedOperationException
Example
import java.util.*; public class Demo { public static void main(String[] s) { Hashtable<String,String>hash = new Hashtable<String,String>(); hash.put("key1", "value1"); hash.put("key2", "value2"); hash.put("key3", "value3"); System.out.println("Initial collection: "+hash); Map map = Collections.unmodifiableMap(hash); // error will generate map.put("key3", "value3"); } }
It will show output with an exception −
Output
Initial collection: {key3=value3, key2=value2, key1=value1} Exception in thread "main" java.lang.UnsupportedOperationException
- Related Questions & Answers
- How can we create an unmodifiable Map in Java 9?
- How can we create an unmodifiable Set in Java 9?
- How can we create an unmodifiable List in Java 9?
- How to create an image map in JavaScript?
- How do we create an image map in HTML?
- Factory method to create Immutable Map in Java SE 9
- Map to create new value from int array in Java
- How to create an Array in Java?
- How to iterate any Map in Java?
- How to Clone a Map in Java
- Get the unmodifiable view of the specified ArrayList in Java
- How to create an immutable class in Java?
- How to create an immutable set in Java?
- How to create an ArrayList from an Array in Java?
- How to use JavaScript to create client-side image map?
Advertisements