1

I have a Java enum called entry. My goal is to have a function which changes the enum value to the other one. In case my enum value is X, I want it to become Y and vice versa. The code I tried to write is here. But this would not compile and it says variable expected in the place where I have used this.

public enum Entry {
    X,
    O;

    public void switchEntry(){
        this == Entry.X? this = Entry.O: Entry.X ;
    }
}

Also I want to know if it is possible without using an additional value variable inside my ENUM class. Thank you. Apologies if it is a stupid question.

  • @Jens There are times when you might want to toggle between two values such as `BLACK` and `WHITE` like a chess board, or `ON` and `OFF` like an electrical switch. – Basil Bourque Dec 12 '20 at 07:42

3 Answers3

5

You cannot switch the value of an enum itself. What you can do, is use the enum in a class and witch the value there:

class Test {

    private Entry entry = Entry.X;

    public void switchEntry() {
        entry = entry == Entry.X ? Entry.O : Entry.X;
    }
}

enum Entry {
    X, O;
}

P.J.Meisch
  • 18,013
  • 6
  • 50
  • 66
3

You can't change an enum to another enum. You can however update an enum variable to refer to another enum value.

public enum Entry {
    X,
    O;

    public Entry switchEntry() {
        return (this == X ? O : X);
    }
}
Entry e = Entry.X;

e = e.switchEntry();
Andreas
  • 154,647
  • 11
  • 152
  • 247
0

The major thing that stops you from doing this, is that this is final. You can't reassign this. There are good reasons for this restriction.

However, even if you could reassign this, your method doesn't make much sense, because there are only two instances of Entry, ever - Entry.X and Entry.O:

§8.9

An enum type has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type

So if you did:

Entry.X.switchEntry();

You would not be able to access the object originally referenced by Entry.X from that point onwards! Because switchEntry sets Entry.X to Entry.O! Now both Entry.X and Entry.O refers to the same object!

And what about if I have a class that contains a getEntry method, that returns a private field entry, without a setter for entry. What if you called (and this is perfectly valid Java code):

getEntry().switchEntry();

Would that set my private entry variable? If so you've just broken encapsulation! Or would it do something stupid like getEntry() = Entry.O;?

Do you see the problem with allowing your implementation of switchEntry?

Anyway, you should instead write a method that returns an instance of Entry. You can then use = at the call site to assign to whatever you like.

Sweeper
  • 213,210
  • 22
  • 193
  • 313