aspose file tools*
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 Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Readonly unmodifiable collection" Watch "Readonly unmodifiable collection" New topic
Author

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();
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

Joined: Oct 13, 2005
Posts: 40052
    
  28
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).
eg


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

Joined: Oct 27, 2005
Posts: 19784
    
  20

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


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Readonly unmodifiable collection