Deleting elements from Hash Set
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Akshay_Rao
Posted On:   Sunday, August 4, 2002 11:00 PM

I am inserting objects of type Person into a HashSet. This class has an 'equals' method that returns true or false based on its instance variable 'name' of type String. Now, if I try to insert an object of type Person into the HashSet, no problem. If i try to remove an object already in the hash set, then there is a problem. It turns out that it will remove the object if I use the same exact reference to specify what object to remove. For instance: Person bob = new Person("Bob"); hashSet.add(bob); hashSet.remove(bob); This code works fine. However, this piece of code does not work: HashSet.add(new Person("Bob")); HashSet.remove(new P   More>>

I am inserting objects of type Person into a HashSet. This class has an 'equals' method that returns true or false based on its instance variable 'name' of type String. Now, if I try to insert an object of type Person into the HashSet, no problem. If i try to remove an object already in the hash set, then there is a problem. It turns out that it will remove the object if I use the same exact reference to specify what object to remove. For instance:



Person bob = new Person("Bob");

hashSet.add(bob);

hashSet.remove(bob);



This code works fine. However, this piece of code does not work:



HashSet.add(new Person("Bob"));

HashSet.remove(new Person("Bob"));



How come? The 'equals' method matches the object based on their 'name' variable.

   <<Less

Re: Deleting elements from Hash Set

Posted By:   Jens_Dibbern  
Posted On:   Monday, August 5, 2002 12:20 AM

AFAIK equal objects are identified by equal hashcodes by the HashSet. Unfortunately this does not follow the Set documentation.



HTH

Jens
About | Sitemap | Contact