java - Comparing an object with a String using equals() method -
in below example, expecting equals()
return true
:
public class flower { string flower; public flower (string flower) { this.flower = flower; } public static void main(string[] args) { flower 1 = new flower("flower"); boolean issame = false; if(one.equals("flower")) { issame = true; } system.out.print(issame); } }
however, result false
... because i'm comparing object string
? read equals()
method , said compare string
s objects
. why getting result false
although same?
the short answer: need override implementation of equals()
in flower
(note: capital f
) class. like do:
@override public boolean equals(object o) { return (o instanceof flower && ((flower)o).flower.equals(flower)) || (o instanceof string && o.equals(flower)); } @override public int hashcode() { return flower.hashcode(); }
overriding hashcode()
equals()
form: generally, 'attributes' (e.g. fields) pick doing equals()
should used in hashcode()
calculation too. in layman terms, should 'agree' each other.
the big/major/severe problem, pointed out practically here presume, equals()
meant symmetric:
it symmetric: non-null reference values
x
,y
,x.equals(y)
should return true if , ify.equals(x)
returns true.
and unfortunately flower
class, string.equals(object)
defined as such:
the result
true
if , if argument notnull
,string
object represents same sequence of characters object. (emphasis mine)
this means no string
ever return true
when pass flower
object equals()
.
sure, can still go against convention, you'll run bugs - minor or major - when learn more language, e.g. collection
classes.
therefore: avoid such comparisons equals()
.
Comments
Post a Comment