Wednesday, 15 February 2012

java - HashSet retainAll using interface -



java - HashSet retainAll using interface -

i have code seek utilize hashset.retainall() function.

in illustration code below, hashset contains interface iperson, equals functions in object person never reached. have tried expose equals function in interface , several other things. sense have tried everything. how can create retainall() utilize implemented equal function?

class person implements iperson { private string name; public person(string name){ this.name = name; } @override public boolean equals(object obj){ system.out.println("calling equals"); homecoming super.equals(object obj); } } hashset<iperson> persons1 = new hashset<iperson>(); persons1.add(new person("jane")); persons1.add(new person("joel")); persons1.add(new person("joe")); hashset<iperson> persons2 = new hashset<iperson>(); persons2.add(new person("jane")); persons2.add(new person("joel")); persons1.retainall(persons2); // expect sysout person.equals() system.out.println(persons1.size()); // prints 0

you need override hashcode because hashset uses hashcode find right 'bucket' first , calls equals after finds in it. that's why equals method never called. (if don't override hashcode method, gives every new object different hashcode, if phone call new person("name") twice same name won't have same hashcode)

java collections equals

No comments:

Post a Comment