• Post Reply Bookmark Topic Watch Topic
  • New Topic

Making Collection final  RSS feed

 
sridhar lakka
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
Thanks a lot.
I have created a Vector as final but still i can able to insert new values from which I came to know that because we are not changing its object reference it is allowing.
But how to make it unmodifiable w.r.to values also.

Please help me out
Regards,
Sree
 
greg buela
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I don't think you can, unless you encapsulate it in a class of your own that includes criteria to determine when the collection can or can not be updated.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't change the Vector to make it unmodifiable, but you can hide it behind an unmodifiable view. As long as the real Vector isn't accessible to any code that might modify it accidentally, things will be fine. See the java.util.Collections.unmodifiableList() method.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by sridhar lakka:
I have created a Vector as final


No, you have a final reference to a Vector object. The "final" applies to the reference. You can't change the reference to point to another Vector.

Java, unlike C++, does not have a way of saying that an object, which is of a class that has methods for changing its contents, is unmodifiable and hence that those methods cannot be called. In C++, there is "const" for this. Sometimes, C++ "const" can be useful and make for nice programs, but often it causes more trouble than it's worth. It's one of the C++ features that the Java designers left out, to make Java smaller and simpler.

By the way, if you are writing new code using Java 1.2 or later, you should never be using Vector. You should be using the similar, but better, ArrayList class.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!