简体   繁体   中英

How can I remove an object of type X from a hashtable given one unique attribute of X in Java?

Let's say I have a class person

public class Person {

int personID = 123;
String fname = John;
String lname = Doe;

}

and I've created a hashtable . (using person as both a key and value). Now, assuming each person has a unique ID and assuming the hashtable is full of persons, I want, given a unique ID (int), to remove the person from the hashtable corresponding to that ID.

The problem arises with what parameters to give the hashtable.remove() function since it takes an object of type Person and not an int.

Note: assume the fact that the key and value are both of type Person is a design requirement and cannot be changed

Edit: I have overriden the hashcode() and equals() method of the person class, they both rely on the personID now. But I still don't know what to pass the hashtable.remove() method since it takes type Person and I want to remove based on a user-given int (which is the personID)

If you have overridden your equals() and hashCode() method based on personID, Then you should simply create a Person Object with the personID your are searching for and search/remove the person accordingly.

Suppose you want to search for 123 personID.

you could Person p = new Person(); p.personID = 123; p.fName = "XYZ"; p.lName = "ABC"; myHashtable.remove(p); Person p = new Person(); p.personID = 123; p.fName = "XYZ"; p.lName = "ABC"; myHashtable.remove(p); As equals() and hashCode() are based on personID. so table would search/remove on the basis of personID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM