Why compare Enum with an enum object

2

When I was learning Java, I had a Class that had a Enum property, and at one point I wanted to know if what was coming in a Method was equal to a Enum constant, something like this:

public void teste( TipoAlteracaoValor valor ) {
        if( valor.equals(TipoAlteracaoValor.ALTERACAO_VALOR) ) {
            System.out.println( "é Alteração ");
        }
        //Deveria ser assim:
        if( TipoAlteracaoValor.ALTERACAO_VALOR.equals(valor)) {
            System.out.println("é Alteração" );
        }
    }

But I was told that this is wrong to do, the right thing is to compare the Enum constant with the value that is coming from the parameter. But I do not remember ... what is the technical reason for using this comparison?

    
asked by anonymous 22.05.2014 / 23:04

2 answers

2

The problem with valor.equals(TipoAlteracaoValor.ALTERACAO_VALOR) is that if the valor parameter is null then you will get a NullPointerException exception for trying to access the equals method on a null object.

The other way solves the problem because the "constant" TipoAlteracaoValor.ALTERACAO_VALOR will never be null and, if the parameter valor is also no problems, simply if will not be executed.

However, I can say that the best way to compare Enums in Java is neither.

You can simply use the == operator, as with primitive types .

The == when applied to objects verifies that they are the same instance. And that's just the advantage of Enum. Each Enum "constant" is actually a single instance of it.

Consider the code:

public void teste( TipoAlteracaoValor valor ) {
    if( valor == TipoAlteracaoValor.ALTERACAO_VALOR ) {
        System.out.println( "é Alteração ");
    }
}

In addition to being readable, it does not incur the problem with null .

Sources on the subject (in English):

22.05.2014 / 23:23
3

When comparing as below, you can take a NullPointerException. Imagine what would happen if the value variable were null:

    if( valor.equals(TipoAlteracaoValor.ALTERACAO_VALOR) ) {
        System.out.println( "é Alteração ");
    }

When comparing the enum with the object that arrived, you avoid taking an error if the attribute is NULL:

    if( TipoAlteracaoValor.ALTERACAO_VALOR.equals(valor)) {
        System.out.println("é Alteração" );
    }

Whether value is null or not, you will have no exception.

Just that. [=

    
22.05.2014 / 23:19