Is there a way to return an immutable hashtable??????
Vinney Shanmugam
Ranch Hand
Joined: Aug 27, 2008
Posts: 104
posted
0
Is there a way to return a non-mutable hashtable. Below is my code and i have got a comment as to return an non-mutable hashtable. I dont have much idea on this. Please help me find this. Are there any classes avilable to acheive this???
>>>>>>>>>>>>>>>>
private Hashtable list_users;
public Hashtable getUsers() {
//TODO
// Is it prudent to return an object of type Hashtable. This makes the contents of the hashtable vulnerable ???
// It is better to return a non-mutable hashtable
return list_users;
}
>>>>>>>>>>>>>>>>
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
4
posted
0
Don't know. It is worthwhile going through the Java Tutorials for collections, and also the Map interface. There are some methods in Collections which return a read-only Collection, which can only me altered by its "home" class and not by the recipient. There might be away to do that with Maps; I don't know.
Alternatively, create a wrapper class which implements Map, and throw an Exception (UnsupportedOperationException) if anybody uses the put remove clear, etc methods.
Actually, I think this question is too difficult for beginners: moving it.
Well, java.util.Hashtable implements the java.util.Map interface, so you can use the java.utilCollections#unmodifiableMap to return an immutable view of a Hashtable.
You should be aware that any attempts to structurally modify the Hashtable via the reference returned by the unmodifiableMap() method will cause an UnsupportedOperationException.
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Vinney Shanmugam
Ranch Hand
Joined: Aug 27, 2008
Posts: 104
posted
0
thanks for your replies....
yeah, i googled and found some useful information....
we can use Collections.unmodifiablemap() method which will return a map which can't be tampered with.
Still if there are any valuable inputs please give them.....
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
4
posted
0
vinod shan wrote:thanks for your replies....
subject: Is there a way to return an immutable hashtable??????