java - equals() and == for the class object -
i have enumeration emulation class. both objects in main p , pp passing ==
, equals
test. both tests passed in case when
p = packettype.none; pp = packettype.none;
and both prints nothing in case
p = packettype.startofoperation; pp = packettype.none;
what invoked in method equals
, operator ==
? think ==
should not pas because must if object have same pointer. in other words should same object (and in our case not).
public class packettype { string name = "9"; public static final packettype none = new packettype("9"); public static final packettype startofoperation = new packettype("1"); packettype(string name) { this.name = name; } public string tostring() { return name; } public static void main(string[] args) { packettype p = packettype.none; packettype pp = packettype.startofoperation; if (p == pp) { system.out.print("=="); } if (p.equals(pp)) { system.out.print("equals"); } } }
with objects ==
should used test whether references same instance of object. .equals(object o)
should used check whether have equal value (however behaviour must implemented manually in custom objects, else defaults ==
behaviour).
a example of string
people commonly make mistake of using ==
on .equals(object o)
when trying check if strings equivalent.
string = "my string"; string b = "my string"; string c = a; //each of these should evaluate true a==c b!=c a.equals(b) b.equals(c)
a full explanation of equals(object o)
method can found here, can't find equivalent equality operator ==
(this one vague , refers primitives not objects).
Comments
Post a Comment