2

I have Enum

public class TestResult {

    MY_ENUM {
        @Override
        public String toString() {
            return "Test1";
        }

        @Override
        public boolean isTested() {
            return true;
        }

        public abstract boolean isTested();
    }
    private MY_ENUM myEnum;
    public MY_ENUM getMyEnum() {
        return myEnum ;
    }
}

I have other class the keep the varaible

public class Result {
    private final TestResult testResult ;
}

I want to check if testResult.getMyEnum() equal TestResult.MY_ENUM. Do I need to do it :

 1 .  testResult.getMyEnum() == TestResult.MY_ENUM.

Does it check the value of toString and isTested?

2.   testResult.getMyEnum().toString().equal(TestResult.MY_ENUM.toString()) 


3.  testResult.getMyEnum().equal(TestResult.MY_ENUM)

Does it check the value of toString and isTested?

Erick G. Hagstrom
  • 4,873
  • 1
  • 24
  • 38
user1365697
  • 5,819
  • 15
  • 60
  • 96
  • The enum is more complex in this case and have some methods and not enum Color { BLACK, WHITE }; – user1365697 Mar 22 '16 at 07:40
  • 4
    This doesn't matter. Every enum value is a single object instance. If you have multiple variables referring to the same object instance, there is no need to call any methods to compare them. – yole Mar 22 '16 at 07:43
  • but does the == will compare all the methods ? – user1365697 Mar 22 '16 at 07:57
  • 2
    You have two variables pointing to the **same object**. You do not need to call all the methods to see that they point to the same object. (No, the == operation will not call any methods.) – yole Mar 22 '16 at 08:57
  • so what the == will check in this case ? – user1365697 Mar 22 '16 at 09:31
  • 2
    In this case, as well as in all other cases, == checks that two variables are pointing to the same object. – yole Mar 22 '16 at 09:33
  • I fixed my question sorry I need to check if other class that have this variable need to compare the enum – user1365697 Mar 22 '16 at 09:34
  • 1
    Everything I said above is still valid. – yole Mar 22 '16 at 09:40
  • 1
    There are _so many_ syntax errors in this! You should post code that compiles, unless you're asking a question about a compilation error (and you're not). – Erick G. Hagstrom Mar 22 '16 at 09:48
  • 1
    As @ErickG.Hagstrom has mentioned, this code is very confusing as it wont even compile. Edit the question with the actual code. As for the answer, as many had already mentioned in the comment, every entry in an enum refers to a single instance of the enum type. So == will return true if both the variables point to the same enum instance. Also, using == is the recommended way to check if the variables are pointing to the same enum instance. – Amudhan Mar 22 '16 at 10:09

1 Answers1

1

Both are correct, .equals() defers to ==.

== would avoid NullPointerException

awsome
  • 2,143
  • 2
  • 23
  • 41