java - Comparing two different objects using contains(Object o) returns false, when equals(Object o) returns true -
[fixed problem below]
i have class:
class doc() { private string d; doc(string d) { d = d; } @override public boolean equals(object o) { if (o instanceof string) { if (o.equals(d)) return true; else return false; } else return false; } @override public int hashcode() { ... } } if run test, initiating doc() using e.g. "abc" parameter , use doc().equals("abc") returns true - expect. if use:
arraylist docs = new arraylist<doc>(); doc d = new doc("123"); docs.add(d); system.out.println(docs.contains("123")); it returns false, , quite unsure of why. have tried adding output .equals() method check if used, , is. code hashcode() bogus (i know should proper, i'm not sure how) - ever going use equals().
i read somewhere equals() checks hashcode(), however; if add system.out.println(".") first line in hashcode() doesn't output anything, doesn't seem called. best guess can't compare 2 objects of different class - correct? or overlooking else?
for future reference, problem solved using suggestion of @jonskeet - code now:
class doc() { private string d; doc(string d) { d = d; } public string getd() { return d; } @override public boolean equals(object o) { if (o instanceof doc) { doc tmp = (doc) o; if (tmp.getd().equals(d)) return true; else return false; } else return false; } @override public int hashcode() { ... } }
you're assuming contains() call memberincollection.equals(candidate) rather candidate.equals(memberincollection). documentation goes against that:
more formally, returns true if , if list contains @ least 1 element e such
(o==null ? e==null : o.equals(e)).
fundamentally, equals method breaks normal contract, because isn't symmetric - non-null values of x , y, x.equals(y) == y.equals(x) should true. that's not case code:
new doc("123").equals("123") // true "123".equals(new doc("123")) // false (additionally, equals method isn't reflexive - x.equals(x) never true if x reference instance of doc.)
basically, shouldn't try make instance of 1 type equal instance of unrelated type. end badly. it's hard enough make equality work nicely within type hierarchy - unrelated types it's really bad idea.
Comments
Post a Comment