4

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?

domsson
  • 4,553
  • 2
  • 22
  • 40

3 Answers3

5

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.

M A
  • 71,713
  • 13
  • 134
  • 174
  • Enums are implicitly [public static final](http://stackoverflow.com/questions/8272957/are-instances-of-enums-static-by-default). Thats probably why he doesn't see the warning. – yxre Jun 26 '15 at 18:28
  • FYI, I'm using Android Studio and it does not give me a warning. Anyway, thanks for your answer (which happens to be pretty much identical to the one that came in a minute before yours). – domsson Jun 26 '15 at 18:51
2
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.

yxre
  • 3,576
  • 21
  • 20
2

Do not use Enum in android http://developer.android.com/training/articles/memory.html#Overhead

(I couldnt do comments because of reputation problem so i wrote here. )

donmezburak
  • 159
  • 1
  • 13
  • Now you can make comments – rpax Jun 26 '15 at 19:07
  • google says : Enums often require more than twice as much memory as static constants. So we should avoid of using it. As an example from android developers, i can say that we are using serVisibility() method. It requires int variable. but we are giving Visible, invisible or gone. They are not enums. So , android developers are also using int instead of enum – donmezburak Jun 27 '15 at 21:47
  • Although that isn't an answer to the question at hand, I do appreciate that piece of information as I wasn't aware of that at all. Thanks! – domsson Jun 28 '15 at 13:15