Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining Java enums with dot syntax (enum.value1.value2)?

I'm going through some existing (and working) code and came across a line like this:

if (someObject.getStatus() == SomeEnum.VALUE1.VALUE2) { ... }

Where SomeEnum is a simple enum that looks like this:

public enum SomeEnum {
    VALUE1,
    VALUE2,
    VALUE3,
    ...
}

private SomeEnum() {}

Now, what does that comparison above do? More precisely, what does the combination of two enum values in there do? I was astonished to not see any warnings or errors because of that line as I assumed this was simply wrong. However, it compiles and runs just fine. Can someone enlighten me on what this would do?

like image 589
domsson Avatar asked Jan 08 '23 01:01

domsson


2 Answers

You should get a warning about this if you're using an IDE like Eclipse, saying that VALUE2 should be accessed in a static way. With javac -Xlint:all you will also get a warning. Other than this, SomeEnum.VALUE1.VALUE2 is exactly the same as SomeEnum.VALUE2. The enum constants are represented as static fields.

like image 67
M A Avatar answered Jan 26 '23 11:01

M A


if (someObject.getStatus() == SomeEnum.VALUE1.VALUE2) { ... }

is equivalent to

if (someObject.getStatus() == SomeEnum.VALUE2) { ... }

== will compare the memory address on both sides for non-primitive types.

like image 42
Leland Barton Avatar answered Jan 26 '23 11:01

Leland Barton