• Post Reply Bookmark Topic Watch Topic
  • New Topic

Is there a way to return an immutable hashtable??????  RSS feed

 
Vinney Shanmugam
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Vinney Shanmugam
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
vinod shan wrote:thanks for your replies....
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!