When adding system function does not compile

Asked

Viewed 115 times

2

I have the following class:

package br.com.xti.ouvidoria.helper;

import java.util.Collection;

/**
 * @author Samuel Correia Guimarães
 */
public class ValidacaoHelper {

    /**
     * @param obj
     *            objeto a ser validado
     * @return TRUE se o objeto passado por parâmetro for NULL, VAZIO
     *         (Collections, Arrays, Strings) ou menor/igual a zero para tipos
     *         númericos
     */
    public static boolean isEmpty(Object obj) {
        boolean vazio = false;

        if (obj == null) {
            vazio = true;
        } else {
            if (obj instanceof String) {
                vazio = ((String) obj).replaceAll("\\s+", " ").trim().isEmpty();
            } else if (obj instanceof Number) {
                if (((Number) obj).longValue() == 0)
                    vazio = true;
            } else if (obj instanceof Collection<?>) {
                Collection<?> col = (Collection<?>) obj;
                vazio = (col == null || col.isEmpty());
            } else if (obj instanceof Object[]) {
                vazio = (((Object[]) obj).length == 0);
            }

        }
        return vazio;
    }

    /**
     * @param objs
     *            objetos a serem validados
     * @return TRUE se algum dos objetos passados por parâmetro for NULL ou
     *         VAZIO
     */
    public static boolean isEmpty(Object... objs) {
        boolean isEmpty = false;
        for (Object obj : objs) {
            isEmpty = isEmpty(obj);
            if (isEmpty) {
                break;
            }
        }
        return isEmpty;
    }

    /**
     * @param obj
     *            objeto a ser validado
     * @return TRUE se o objeto passado por parâmetro for diferente de NULL,
     *         VAZIO (Collections, Arrays, Strings) e maior que zero para tipos
     *         númericos
     */
    public static boolean isNotEmpty(Object obj) {
        return !isEmpty(obj);
    }

I wanted to add to it the following function:

public static boolean saoIguais(Integer obj, Integer obj2) {
    boolean iguais = false;

    if (obj == obj2) {
        iguais = true;
    } 
    return iguais;
}

But how is the system nor compiles!

If I put as Object instead of Integer it compiles:

public static boolean saoIguais(Object obj, Object obj2) {
    boolean iguais = false;

    if (obj == obj2) {
        iguais = true;
    } 
    return iguais;
}

But in that case the comparison never returns as true.

  • 1

    What error and compilation it produces?

  • 1

    Because you don’t use the method Object.equals(Object, Object) which is already ready, is already in the standard library and already does what you want?

  • @Victorstafusa I was mistaken in my data entry so I thought something was wrong

  • But the main of my question still not understood that is the pq using the (Integer obj, Integer obj2) the system does not compile

  • 1

    And what is the build error in this case?

2 answers

2


The == operator in non-priminal types compares only the reference of the object, not its equality. When you do obj1 == obj2, you are only comparing if the obj1 pointer points to the same memory address as obj2, regardless of the value of each object. To compare equality, use the equals method:

    boolean saoIguais = obj1.equals(obj2);
  • My mistake, the return of one of the objects was different than expected by that error, with the equals compared right

  • Beware of the nulls being passed as well. It is necessary to check for them, for example if the 1st object is null, will have a NullPointerException

0

The error of comparison is exactly what Orlando answered, when you compare a variable of complex types like objects you compare their memory references. To compare if the values are equal the correct is you override the equals method. But in your case like this comparing an Integer it already overrides the equals and compares the content of the object.

I took your method and made an implementation with the given suggestion and validating the nullity of the object:

    public static boolean saoIguais(Integer obj, Integer obj2) {
    //Se quiser considerar que os dois valores nulos são iguais então use o if abaixo
    if(obj == null && obj2 == null )
        return true;
    //Este if é obrigatório para validar se o objeto é nulo
    if(obj == null || obj2 == null )
        return false;
    //Compara os valores usando a implementação equal da classe Integer
    return obj.equals(obj2);
}

Browser other questions tagged

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