Why compare Enum with an Enum Object

Asked

Viewed 1,812 times

2

When I was learning Java, I had a Class that had a property like Enum, and, at a certain point, I wondered if what was coming in a Method was equal to a constant of the Enum, something like that:

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, it is right to compare the Constant of the Enum with the value that is coming from the parameter. However I don’t remember... what is the technical reason for using this comparison?

2 answers

3

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

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

When comparing Enum with the incoming object, you avoid making 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.

That’s all. [=

  • Nothing but an additional check valor != null do not resolve (with the disadvantage of you having to make this additional check :)

  • Uhum. I still prefer it without checking, it’s one if less. : 3

2


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

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

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

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

The == when applied to objects checks if they are the same instance. And that is precisely the advantage of Enum. Each "constant" of the Enum is actually a unique instance of the same.

Consider the code:

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

Besides more readable it does not incur the problem with null.


Sources on the subject (in English):

Browser other questions tagged

You are not signed in. Login or sign up in order to post.