Reputation:
I have a really strange enum bug in Java.
for(Answer ans : assessmentResult.getAnswersAsList()) { //originally stored in a table
//AnswerStatus stat = ans.getStatus();
if (ans.getStatus() == AnswerStatus.NOT_ASSESSED) {
assessed = false;
}
}
An answer is an answer to a question on a test. An assessment result is the result a student gets on a test (this includes a collection of answers).
I've debugged the above code, and ans.getStatus()
returns AnswerStatus.ASSESSED
.
Still, the if line returns true, and assessed is set to false.
But, the thing I think is most strange; When I declare the AnswerStatus
stat variable, it works, even if I don't use the stat variable in the if test. Could someone tell me what is going on?.
I've read something about enum bugs in serialization/RMI-IIOP but I don't use that here.
The enum AnswerStatus
can be ASSESSED
or NOT_ASSESSED
.
The getStatus
method in class Answer
just returns the status, nothing else.
Upvotes: 0
Views: 1788
Reputation: 3827
No answer to your question but a suggestion:
It's always better to place the fix enum value in the first place in the compare statement and the variable part in the second place. Because, if in any circumstance the variable part delivers NULL you won't get a NullPointerException.
In your example it will look like this
...
if (AnswerStatus.NOT_ASSESSED == ans.getStatus())
...
MISTAKE:
Of course I make a mistake and mixed two things with each other. If you use the equals method to compare a fixed enum value with a variable containing this enum it's good to compare the constant enum value with the variable and not vic versa. For example:
write
if (AnswerStatus.NOT_ASSESSED.equals(ans.getStatus()))
instead of
if (ans.getStatus().equals(AnswerStatus.NOT_ASSESSED))
because, this could harm a NullPointerException if ans.getStatus() == null.
Upvotes: -4
Reputation:
Solved.
It was the NetBeans debugger that tricked me. It does not pass the if test (although NetBeans says that).
Sorry for the inconvenience :-)
Upvotes: 2
Reputation: 346387
I've debugged the above code, and ans.getStatus() returns AnswerStatus.ASSESSED. Still, the if line returns true, and assessed is set to false.
But, the thing I think is most strange; When I declare the AnswerStatus stat variable, it works, even if I don't use the stat variable in the if test. Could someone tell me what is going on?.
This sounds like the getStatus()
method does not always return the same result - how is it implemented?
BTW, what's the point in having an enum with the values ASSESSED, and NOT_ASSESSED? Why not use a boolean isAssessed()?
Upvotes: 2