This may be a stupid question but one that is throwing me for a loop.
I have implemented a singleton class (I know they are evil) using an enum in Java as follows
public enum Edit {
INSTANCE;
private TreeSet<String> list1 = new TreeSet<String>();
public void createList(Scanner input) {
while (input.hasNext()) {
list1.add(input.next());
}
My question is what happens with the TreeSet when you use the createList method in more than one place in the application?
For example say the first time Edit.INSTANCE.createList() is called in the application,10 Strings are added to list1, now the second time it is called, 5 Strings are added to list1….will those new 5 strings be added to the TreeSet with the previous 10 Strings or will they be added to a completely different (new) TreeSet?
I know the purpose of a singleton class is to make sure that there is one and only one global instance of the class but does that hold true for the class member variables? Is there only one copy of list1 in the above example or each time the createList() method is called is a new TreeSet created?
There’s just a single instance of the
Edittype, so there’s a singleTreeSet<String>.Each time you call
createList, it will add more values to the sameTreeSet.You say:
If it didn’t hold for member variables, what would be the point? That’s what’s interesting about a single instance – it has its own state.
In general, it’s a very bad idea for an enum to be mutable – usually they’re meant to represent specific values, potentially with behaviour. Likewise I rarely have mutable singletons – it introduces threading issues etc, as you naturally have shared state.