Skip to content

Instantly share code, notes, and snippets.

@miho
Created July 16, 2012 11:52
Show Gist options
  • Save miho/3122281 to your computer and use it in GitHub Desktop.
Save miho/3122281 to your computer and use it in GitHub Desktop.
Unmodifiable Map Sample
/**
*
* @author Michael Hoffer <[email protected]>
*/
public class UnmodifiableMapSample {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
TestClass t1 = new TestClass();
System.out.println("Map:\n" + t1.toString());
System.out.println("Trying to modify map:");
t1.getReadOnlyMap().put("D", "ValueD");
}
static class TestClass {
private Map<String, String> map = new HashMap<String, String>();
public TestClass() {
map.put("A", "ValueA");
map.put("B", "ValueB");
map.put("C", "ValueC");
}
@Override
public String toString() {
String result = super.toString() + ":\n";
for(String key : map.keySet()) {
result += "Key:" + key + " = Value:" + map.get(key) + "\n";
}
return result;
}
public Map<String, String> getReadOnlyMap() {
return Collections.unmodifiableMap(map);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment