Comparison between Objects always returns false

Asked

Viewed 41 times

-1

Why even with that: ValidacaoHelper.saoIguais(3044, 3044), that is, with equal parameters, the 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;
}
  • To compare objects use instanceof

  • @Netinhosantos with instanceof did not work either, actually gave error

1 answer

1


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

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

That’s how it 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;
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • I think I get it, it works like a pointer

  • But without being able to do as in your example, receiving the values from different sources and having to compare the content has how to do?

  • Has if you receive types by value and not by reference, that the case of Object. Maybe it was the case. Another possibility is to make a cast on the object for a type that allows to compare the same values, but does not make much sense in this case. It could still have a specific type with a method equals() that compares the right things, but also doesn’t seem to fit. To tell the truth I don’t know why you’re using a Object.

  • In this question I explain the pq: https://answall.com/questions/237780/ao-addir-fun%C3%A7%C3%A3o-system-n%C3%A3o-compila

Browser other questions tagged

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