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]
# 1
Do you know how final objects work? Maybe you want the Strings inside the Set to be final?
CaptainMorgan08a at 2007-7-8 22:52:21 > top of Java-index,Java Essentials,New To Java...
# 2

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.

cumina at 2007-7-8 22:52:21 > top of Java-index,Java Essentials,New To Java...
# 3

> 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

}

prometheuzza at 2007-7-8 22:52:21 > top of Java-index,Java Essentials,New To Java...
# 4

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

JosAHa at 2007-7-8 22:52:21 > top of Java-index,Java Essentials,New To Java...
# 5

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.

cumina at 2007-7-8 22:52:21 > top of Java-index,Java Essentials,New To Java...
# 6
If you don't want each object to have its own copy of the Set object you may want to declare it static final.
cumina at 2007-7-8 22:52:21 > top of Java-index,Java Essentials,New To Java...