populating the values of a final Set<String>
I want to make a Set<String> whose values cannot be modified. I declare an instance variable as
final Set<String> theValues;
I need to set the values somehow; I'd like to do so in the constructor which is called only once in the program. However, I do not know how to declare the Set and populate its values all in one statement, which seems to be what the compiler wants.
How can I populate a final Set<String>?
[491 byte] By [
cumina] at [2007-11-26 16:28:03]

I want a set whose elements can't be changed.
I think I know how final works in the case of a constant:
final double PI = 3.1415926;
but I don't know how to make it work to do this. I guess I am fuzzy on final objects vs final primitives.
Making the Strings in the Set constant seems like it would not prevent the addition of new strings to the set or the removal of strings from the set.
> I want a set whose elements can't be changed.
Strings themselves cannot be changed.
Perhaps you mean you want a set which does not support the removing of elements, but adding them to the set is allowed?
If this is the case, you could do something like this:
public class MySet<E> extends HashSet<E> {
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException(
"Cannot remove elements from this set.");
}
// other overridden methods
}
How about this:final Set<String> yourSet;
{
Set tmp<String>= new Set<String>() {
add("foo");
add("bar");
};
yourSet= Collections.unmodifiableSet(tmp);
}
Now your set will be final (no other set can be assigned to it) and none
of its elements can be changed (added or removed).
kind regards,
Jos
That is exactly what I was looking for. JosAH. Your explanation is clear and succinct and right on.
Gogle led me this thread
http://forum.java.sun.com/thread.jspa?threadID=511756&messageID=2442259
which helped me distinguish between
1) preventing a name or reference from pointing to something else ("final"), and
2) preventing an object's state from being modified, specifically preventing a Collection from being modified
Thanks.