Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Make a Hashtable read-only in Java
Read-only Hashtable would mean users won’t be able to add or remove elements from it. Let us first create a Hashtable with key-value pair −
Hashtable<String, String>hash = new Hashtable<String, String>();
hash.put("1", "A");
hash.put("2", "B");
hash.put("3", "C");
hash.put("4", "D");
hash.put("5", "E");
hash.put("6", "F");
hash.put("7", "G");
Now, use unmodifiableMap() to form a Hashtable read-only −
Map<String, String>m = Collections.unmodifiableMap(hash);
Example
import java.util.Collections;
import java.util.Hashtable;
import java.util.Map;
public class Demo {
public static void main(String[] s) {
Hashtable<String, String>hash = new Hashtable<String, String>();
hash.put("1", "A");
hash.put("2", "B");
hash.put("3", "C");
hash.put("4", "D");
hash.put("5", "E");
hash.put("6", "F");
hash.put("7", "G");
hash.put("8", "H");
hash.put("9", "I");
hash.put("10", "J");
System.out.println("Hashtable = " + hash);
Map<String, String>m = Collections.unmodifiableMap(hash);
System.out.println("Hashtable is now read-only!");
}
}
Output
Hashtable = {9=I, 8=H, 7=G, 6=F, 5=E, 4=D, 3=C, 2=B, 10=J, 1=A}
Hashtable is now read-only!Advertisements