• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

immutability and passing of lists

 
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How can I maintain immutability of objects when they contain lists that must be made available to clients of the class?
For example, I have a class that has an ArrayList of documents, and it has a method:
<code>public List getDocuments() </code>
Of course, someone can obtain the reference to the list, get an Iterator, and begin removing anything they want. It seems to me as though this violates the public/private interface.
Is there an easy way to prevent this sort of tampering? I could extend ArrayList to disallow add/remove and implement my own Iterator class that refuses the remove option, but this seems like overkill. Is there a better way to do it? Are there any Java books that discuss this?
Thanks,
Micah
[ July 22, 2002: Message edited by: Micah Wedemeyer ]
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Check out Collections.unmodifiableList(). Of course, this will only really work if the objects within the list are also immutable. If that's not the case, you could make a deep copy of the list - i.e. make a copy of each object in the list, and put it in a new list. Do not rely on the default clone() implementation in Object, unless you're sure that the objects in question contain no references to other muatable objects.
 
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Jim Yingst:
Check out Collections.unmodifiableList().


Yes, change your getDocuments method so that it has the following line
return Collections.unmodifiableList( myDocumentList)................
 
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Another possibility is to pass the method a clone of the original list.
-Stu
 
When people don’t understand what you are doing they call you crazy. But this tiny ad just doesn't care:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic