java - 无法从 HashMap 中删除元素

标签 java hashmap element

我创建了一个 HashMap 来存储对象 Person,键是一个字符串(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!");
    }
}       

我的输出:

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]

最佳答案

Object obj = personDB.remove(personDB.get(mail)); 

应该是

Object obj = personDB.remove(mail); 

remove 的参数是key,而不是元素。

关于java - 无法从 HashMap 中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10540004/

相关文章:

javascript - 带有基于输入值的前缀名称的 jQuery addClass

java - 在java中移动数组列表的元素

java - Gradle:将 native 库与现有的外部库链接

java - 什么是NullPointerException,我该如何解决?

java - 自动化截图

java - 处理大型 HashMap 的内存高效方式

java - 第二个自动连接的 REST 存储库不工作

带有 Int 数组的 Java HashMap

arrays - 提高在结构 slice 中搜索值的性能

xml - 如何获得XPATH中子项最多的ELEMENT?