| Author |
effect of overriding equals on Sets?
|
Deepak Bajoria
Ranch Hand
Joined: Mar 07, 2008
Posts: 35
|
|
What is the effect of overrding equals method on Set. I mean, Can a set have objects which are different but are "meaningfully" equal. The equals() has been correctly overridden i n the custom class to test the "meaningful equality" Thanks in advance [ July 23, 2008: Message edited by: Deepak Bajoria ]
|
SCJP 5 - 93%
|
 |
Taariq San
Ranch Hand
Joined: Nov 20, 2007
Posts: 189
|
|
Originally posted by Deepak Bajoria: What is the effect of overrding equals method on Set. I mean, Can a set have objects which are different but are "meaningfully" equal. The equals() has been correctly overridden i n the custom class to test the "meaningful equality" Thanks in advance
Nope, javadoc says...
boolean add(E e) Adds the specified element to this set if it is not already present (optional operation). More formally, adds the specified element e to this set if the set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.
|
 |
Deepak Bajoria
Ranch Hand
Joined: Mar 07, 2008
Posts: 35
|
|
But see here this code: This produces the output: Size:1 Size:2 Two objects here obj and obj1 are meaningfully equal, But they have been added to the set. [ July 23, 2008: Message edited by: Deepak Bajoria ]
|
 |
Raphael Rabadan
Ranch Hand
Joined: Jul 05, 2008
Posts: 141
|
|
Originally posted by Deepak Bajoria: But see here this code: This produces the output: Size:1 Size:2 Two objects here obj and obj1 are meaningfully equal, But they have been added to the set. [ July 23, 2008: Message edited by: Deepak Bajoria ]
When you use anything based on Hash you should override the method hashCode respecting the contract between hashCode and equals. Study them. Take a look at this topic too, here I explained a bit: http://www.coderanch.com/t/269571/java-programmer-SCJP/certification/Do-have-override-equals-due
|
SCJP Java 6 (98%) - Story, SCJA (88%) - Story
|
 |
Deepak Bajoria
Ranch Hand
Joined: Mar 07, 2008
Posts: 35
|
|
|
Thanks Raphael, for pointing out
|
 |
kaushik vira
Ranch Hand
Joined: Feb 01, 2007
Posts: 102
|
|
import java.util.*; class AB { int i; public boolean equals(Object o){ if(!(o instanceof AB)) return false; return ((AB)o).i==i; } @Override public int hashCode() { return i; } AB(int i){this.i=i;} } public class demo5 { public static void main(String []args){ HashSet<AB> s=new HashSet<AB>(); AB obj1=new AB(6); s.add(obj1); System.out.println("Size:"+s.size()); AB obj=new AB(6); s.add(obj); System.out.println("Size:"+s.size()); } } Now your program will work as you want.
|
kaushik Vira
-------------------------------------
SCJP, Preparing SCWCD..
|
 |
 |
|
|
subject: effect of overriding equals on Sets?
|
|
|