Re: .equals(o) and Set membership

From: hiwa (HGA03630_at_nifty.ne.jp)
Date: 12/05/03


Date: 4 Dec 2003 22:26:04 -0800

Murat Tasan <tasan@eecs.cwru.edu> wrote in message news:<Pine.SOL.4.53.0312041520470.18529@homer>...
> i have a class, in which i have override the Object.equals(Object o)
> method... and then i try to make two equal objects (under the new
> definition) and place them into a HashSet... which should only accept one
> of them, as in the following code. the class holds two objects (a pair of
> objects) and if another member of the class contains the same two objects
> (in either place of the ordered pair), it is considered equal.
>
> Integer key1 = new Integer(1);
> Integer key2 = new Integer(2);
> HashSet x = new HashSet();
> // demonstrate that the equals() method works...
> System.out.println((new MyClass(key1, key2)).equals(new myClass(key2,
> key1)));
> System.out.println(x.add(new MyClass(key1, key2)));
> System.out.println(x.add(new MyClass(key2, key1)));
>
>
> if i'm correct in reading the docs about how Set classes work, the output
> of this should be:
>
> true
> true
> false
>
> but instead i'm getting:
>
> true
> true
> true
>
> and indeed the Set x has two elements after this code.
>
> i thought the Set code checks for membership by applying the .equals()
> method, which at runtime should bind to my overridden method, no?
>
> thanks for any help,
>
> murat

Sorry, my previous reply is wrong. Java.util.HashXxx data structure
classes check hashCode() of the added/stored objects. See javadoc for
Object#hashCode() and source files HashSet.java and HashMap.java. The
former depends on the latter in logic reuse.



Relevant Pages

  • RE: VS 2005 Classname Drop down
    ... In VB.NET 2005, to override a method/property in an inherited class, open ... member in the list. ... Microsoft Online Community Support ... where an initial response from the community or a Microsoft Support ...
    (microsoft.public.dotnet.general)
  • Overriding interface members
    ... And I want to override ... Declaring the member with override, ... my interface member completely replaces the member ... from the base class. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: denying inheritance
    ... "Gary Labowitz" writes: ... and still override the member ... >> Not having a virtual destructor really should keep sane people ...
    (alt.comp.lang.learn.c-cpp)
  • Re: denying inheritance
    ... "Micah Cowan" wrote in message ... and still override the member ... Dumb question: can you inherit from a class if you don't have the source? ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Swing - paintComponent not called
    ... The usual reason an overridden method never gets called is you changed ... the signature slightly so it does not actually override the base ... point moot:) ...
    (comp.lang.java.programmer)