Question

I have a bean class say User.java

class User{
String a;
String b
String c;
...
}

how i use it in code,

function foo1(){

User u = new User();
//Getting data from DB and adding it to user class say
u.setA("a");
u.setC("c");
foo2(u)
}


function foo2(User u){

User u1 = new User();
//Getting data from another DB and adding it to user class say
u1.setA("a");
u1.setB("b");

//Compare it here,
Boolean status = u1.equals(u);
u1.toString().equals(u.toString());
}

I noticed that u1.equals(u); returns true and u1.toString().equals(u.toString()) return false,

Can any one please explain it that what is the difference between both comparisons and which is batter to use. I just need to compare if both the beans are same or not(with respect to data).

what if i use u1 == u ... ??? Thanks in advance.

EDIT

public String toString() {
    return this.getA() + "\t" + this.getB() + "\t" + this.getC() + "\t";
}

private boolean equals(String a, String b) {
    // check for both being null
    if (a == null && b == null)
        return true;
    // check for only one of them to be null
    if ((a == null && b != null) || (a != null && b == null))
        return false;
    // check for equals()
    return a.trim().equals(b.trim());
}

public boolean equals(User user) {
    return equals(this.a, user.getA()) && equals(this.b, user.getB())
            && equals(this.c, user.getC());
}
Était-ce utile?

La solution

Calling == is a reference comparison, ie using memory location to decide equality. If both do not contain the same reference, it will return false.

Calling equals on an object instance will use the implementation of equals in that class; if it doesn't have one that overrides the default, it falls back to the generic one in Object. This is the Object.equals description from the docs:

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

In short if you don't implement your own equals method you'll get the default behavior which will behave just like ==. For details on writing your own equals method, check this very comprehensive community wiki.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top