开发者

Java comparing enumerator (Strange behaviour)

I work with a Java project and Eclipse(Version 3.6.2) as IDE, in a enum comparison i get a strange behaviour, following an example of the weirdness :

Global Variable :

StatusType status = StatusType.SIGNATURE;

                     

Code :

                String trsStatus = "END";
            if(trsStatus.equals("END") && (this.status.compareTo(StatusType.SIGNATURE) != 0)){
                //Do something
                }

This comparison succeeds and enter in the if block, Why ? In this case the second evaluation(this.status.compareTo(StatusType.SIGNATURE) != 0) of the if statements fail because the result is false ! Why java however enter in the block ???

If i evaluate the expression on the expression watcher of eclipse debugger the value of the statements are :

trsStatus.equals("END") ---> true

(this.status.compareTo(StatusType.SIGNATURE) != 0) ---> false

I've done another test, if i assign the result of the second expression in the if statements to a boolean variable :

boolean sign = (this.status.compareTo(StatusType.SIGNATURE) != 0);

i get this r开发者_C百科esult :

(this.status.compareTo(StatusType.SIGNATURE) != 0) ---> false

sign ---> true

Why ?!?

How this can be possible ?


Could it be that StatusType overrides compareTo() in some weird way?

Are there any other threads that could be changing the value of the status field?

In any case, you should use equals() or even == rather than compareTo() here.


this.status.compareTo(StatusType.SIGNATURE) != 0 will return zero, because zero means they are equal. compareTo() returns either 1, -1, or 0, based on which value is considered greater.


The only sensible reason I could imagine is that

this.status != StatusType.SIGNATURE

Period. You probably set status to some other value unknowingly. Maybe with another thread. Who knows. What does status evaluate to, in your debugger?

In any case, there is certainly no such "bug" in Java. Unless you post some more code that proves it ;-)


You should use: this.status != StatusType.SIGNATURE.


public class Test {
    public static void main(String[] args) {
        TestEnum e = TestEnum.SIGNATURE;
        System.out.println(e.compareTo(TestEnum.SIGNATURE));
        String test = "test";
        if (test.equals("test") && e.compareTo(TestEnum.SIGNATURE) != 0) {
            System.out.println("I'm here");
        }
    }
}

I did the following test. It does not enter the if block and print "I'm here".

Can you post your snippet?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜