This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Readonly unmodifiable collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Readonly unmodifiable collection" Watch "Readonly unmodifiable collection" New topic

Readonly unmodifiable collection

ramya narayanan
Ranch Hand

Joined: Oct 06, 2008
Posts: 338
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();

If i want to make this collection read-only how to achieve it?
Any help is appreciated.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 45292
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

Joined: Oct 06, 2008
Posts: 338
How programmatically we can achieve that?
Paul Beckett
Ranch Hand

Joined: Jun 14, 2008
Posts: 96
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).

[ October 24, 2008: Message edited by: Paul Beckett ]
Rob Spoor

Joined: Oct 27, 2005
Posts: 20184

I agree with Paul: don't reinvent the wheel. Instead just use the method mentioned earlier:

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Readonly unmodifiable collection
It's not a secret anymore!