Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unmodifiable Vector in Java

Tags:

java

I need to manage data in my program where Java-Vector suits the purpose as it is synchronized,provides dynamic size and fast random access through index.

But I want to make my Vector Read Only for other Program Classes and Read Write for my own Class.

I read about Collections.unmodifiableList() ,but if I make my Vector unmodifiable, it will become read-only to my class as well.

How can I solve this problem?

like image 439
Nargis Avatar asked Dec 26 '22 12:12

Nargis


1 Answers

I read about Collections.unmodifiableList(), but if I make my Vector unmodifiable, it will become read-only to my class as well.

I think you misunderstand what that method does. In reality, it creates an unmodifiable wrapper for the existing list, leaving the original list modifiable.

So the way to handle your requirement is to do something like this1:

private Vector<?> myVector = new Vector<?>();
private List<?> readOnly = Collections.Collections.unmodifiableList((myVector);

public List<?> getList() { return readOnly; }

Anything that has access to myVector can still add and remove elements from it. The changes will be visible via the readonly object ... but "change" operations on that object won't work.

(The other approach is to create copies of the original Vector object, but I'm pretty sure that doesn't meet your requirements.)


1 - Note that the readOnly object is a List but not a Vector. This shouldn't be a problem unless you have made the mistake of declaring the getter as returning a Vector. If you've done that, and you can't correct the mistake, then you will need to create your own subclass of Vector along the line of Evgeniy Dorofeev's answer. Otherwise Collections.unmodifiableList(...) will do just fine.

like image 113
Stephen C Avatar answered Jan 05 '23 20:01

Stephen C