我创建了一个存储对象Person的hashmap,键是一个String(Person的电子邮件地址).我试图使用密钥删除hashmap中的条目,但不确定为什么它不会删除它.什么地方出了错?我的代码和输出都包含在内.任何帮助表示赞赏!
import java.util.HashMap;
import java.util.Map;
public class TestHashMap {
private Map <String, Person> personDB = new HashMap<String, Person>();
// added main to test the code
public static void main(String[] args) {
TestHashMap org = new TestHashMap() ;
// add data to personDB
org.add(new Person("A", "Smith","1234567890","ASmith@atest.com"));
org.add(new Person("B", "Smith","1234567890", "BSmith@atest.com"));
org.add(new Person("C", "Walsh","1234567890","CWalsh@atest.com"));
org.add(new Person("D", "Glatt","1234567890","DGlatt@atest.com"));
org.add(new Person("E", "Cheong", "1234567890","ACheong@atest.com"));
org.add(new Person("F", "Walsh","0123456789","FWalsh@sg.com"));
// remove an element from personDB
org.display("testing ......before remove"); // display all elements in personDB
org.remove("ACheong@atest.com");
org.display("after..................");
}
public void add(Person p) {
String key = p.getEmail();
personDB.put(key, p);
}
public void remove(String mail) {
Object obj = personDB.remove(personDB.get(mail));
System.out.println(obj + " deleted!");
}
}
Run Code Online (Sandbox Code Playgroud)
我的输出:
testing ......before remove("ECheong@atest.com")
ID:[ASmith@atest.com]
ID:[CWalsh@atest.com]
ID:[FWalsh@sg.com]
ID:[ECheong@atest.com]
ID:[DGlatt@atest.com]
ID:[BSmith@atest.com]
null deleted!
after..................
ID:[ASmith@atest.com]
ID:[CWalsh@atest.com]
ID:[FWalsh@sg.com]
ID:[ECheong@atest.com]
ID:[DGlatt@atest.com]
ID:[BSmith@atest.com]
Run Code Online (Sandbox Code Playgroud)
Object obj = personDB.remove(personDB.get(mail));
Run Code Online (Sandbox Code Playgroud)
应该
Object obj = personDB.remove(mail);
Run Code Online (Sandbox Code Playgroud)
参数to remove是key,而不是元素.
| 归档时间: |
|
| 查看次数: |
1102 次 |
| 最近记录: |