Friday, September 12, 2008

== vs. equals() in Java

In JAVA, you may be confused with "==" and equals() all the time. What are they all about?

"==":
For primitive: check the velue

For String:
1.if see any new(means String s = new String("xxx"); -->check if they pointing to same object
2.if see only ""(means String s = "xxx"; ) -->check the string content

For Wrapper:
1. same as String, see any new --> check if they pointing to same object
2, if there is not, then tricky things coming:
2.1, if it is byte, short, int and the value is <=127, -->check the value
2.2, otherwise check the if they pointing to same object

equals():
For primitive: no way to use this

For general Object:
1.must override it to compare the key attribute(s) of object;
2,if collection is Hashxxx, you need override hashCode() too, otherwise equals won't effect

For String and wrappers:
they have well overridden equals() and hashCode()

No comments: