Comparison between Objects always returns false

-1

Why even with this: ValidacaoHelper.saoIguais(3044, 3044) , that is, with equal parameters, return is false ?

/**
 * @param obj
 *            objeto a ser validado
 * @return TRUE se o objetos passados por parâmetro forem iguais
 */
public static boolean saoIguais(Object obj, Object obj2) {
    boolean iguais = false;

    if (obj == obj2) {
        iguais = true;
    } 
    return iguais;
}
    
asked by anonymous 15.09.2017 / 20:57

1 answer

1

Because Object is a type by reference, then the comparison is with the addresses of the objects and not with the values that are within them. Since they are two different objects, they are different addresses, so it is always different.

See more in Memory Allocation in C # - Value Types and Reference Types . It's C #, but it's the same thing, but C # allows you to create your types by value only Java 10 will allow this.

This works, but it's not the way you think, it's not because the value is the same, it's because it's the same object.

class Ideone {
    public static void main (String[] args) {
        Object x = 3044;
        Object y = x;
        System.out.println(saoIguais(x, y));
    }
    public static boolean saoIguais(Object obj, Object obj2) {
        return obj == obj2;
    }
}

See running on ideone . And in Coding Ground . Also I placed in GitHub for future reference .

    
15.09.2017 / 21:05