What is wrong with the operator! = Here?

if(foo != bar)
    Log(foo + " is not equal to " + bar);

Print

FooBar @ ca4c33db is not equal FooBar @ ca4c33db

This happens on Android. FooBar is my own custom class. I double checked it in the debugger.

+3
source share
4 answers

You have to use equals()

if(!foo.equals(bar))

But with, Stringyou can do the following, since the class has Stringimplemented the method equals().

    String a = "hi";
    String b = "hii";
    if (a!=b){
        System.out.println("yes");
    }else {
        System.out.println("no");
    }

Conclusion:

   yes

If you want to go your own way, you must override the method equals().

Example: With Override Canceled equals()

public class Test {
private String name;
private int age;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
 }
}

Now take a look at this

   Test a = new Test();
    Test b = new Test();
    a.setAge(1);
    a.setName("hi");

    b.setAge(1);
    b.setName("hi");
    if (a!=b){
        System.out.println("yes");
    }else {
        System.out.println("no");
    }

Conclusion:

   yes

Now you can see the same problem here.

0
source

The == operator checks whether two object reference variables refer to the same object instance. similarly: = ...

,.equals(), , ,

(! foo.equals(bar))

-1

, .

== , " " ( JVM), .

.equals(), . , .hashCode() Java ( ).

Only if you guaranteed the immutability of your objects and did not create new instances for objects with the same value (for example, logical objects generated with Boolean.valueOf(true/false)), could you use this ==; otherwise you need the .equals () method (or get them to implement Comparable and try foo.compareTo(bar) == 0)

-1
source

Because these are different objects.

Try changing the field / element in one object and see if the field has changed in another object.

-1
source

All Articles