• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Readonly unmodifiable collection

 
ramya narayanan
Ranch Hand
Posts: 338
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it possible to create an collection , which can be only read-only & unmodifiable so that others wouldn't be able to modify it.

Set s=new HashSet();
s.add("Sai");
s.add("jothish");



If i want to make this collection read-only how to achieve it?
Any help is appreciated.
Regards.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50171
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a method in the Collections class which does exactly that; it is called somethingUnmodifiableSomething. You get a Collection the user cannot modify (read-only) but the original Collection can still be modified and that alters the read-only version.
 
ramya narayanan
Ranch Hand
Posts: 338
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How programmatically we can achieve that?
 
Paul Beckett
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Collections.unmodifiableXXX(...) static methods are the way to achieve this (as Campbell Ritchie explained).

I don't know why you'd want to reinvent the wheel but if you want to create your own version of the unmodifiable views then you need to create a new class that implements one of the collections interfaces. You will then need to provide implementations of all of the methods, mostly delegating to the original collection. Methods that will modify the collection will need to throw some kind of exception (convention is UnsupportedOperationException).
eg


[ October 24, 2008: Message edited by: Paul Beckett ]
 
Rob Spoor
Sheriff
Pie
Posts: 20661
64
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Paul: don't reinvent the wheel. Instead just use the method mentioned earlier:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic