views:

241

answers:

3

How to make a Array List read only, so no one can add, edit or delete, once after the initialization in Java

+7  A: 

Pass the ArrayList into Collections.unmodifiableList()

Scobal
"... and only use the returned List, and never the original `ArrayList`" is a very important addition here! Passing the `ArrayList` to that method doesn't magically change the object. It only returns an unmodifiable wrapper.
Joachim Sauer
@Joachim Sauer - great point!
Scobal
Sometimes you want to keep the original `ArrayList`. This can be a great technique for exposing a `List`-like view of data encapsulated within an object. Modifications to the object will update the `List` view, but the view itself does not accept any modifications.
Matthew
A: 

Are you sure you want to using ArrayList in this case?

Maybe it would be better to first populate an ArrayList with all of your information, and then convert the ArrayList into a final array when the Java program initializes

Jama22
HI Jama, I found Collections.unmodifiableList() this will work the way i wanted. try this method, its straight forward
harigm
well i'll be... that's awesome!
Jama22
A: 

Check out Google Collections, and for your needs look at ImmutableList. But everything in there is worth looking at.

Shaun
Shaun, I have about the google collection wuite often in the stack overflow, but First Doubt is Can I use the Google Collections with Java Code? will there be any conflict?
harigm
Yes you can. We use Google Collections extensively in our Java development. No conflicts to worry about.
Shaun