gpt4 book ai didi

java - 关于 Java 中的 Hashmap 的帮助

转载 作者:行者123 更新时间:2023-12-01 07:42:13 25 4
gpt4 key购买 nike

我不确定如何使用 get() 来获取我的信息。看我的书,他们将 key 传递给 get()。我认为 get() 返回与查看文档的该键关联的对象。但我一定在这里做错了什么......有什么想法吗?

import java.util.*;

public class OrganizeThis
{
/**
Add a person to the organizer

@param p A person object
*/
public void add(Person p)
{
staff.put(p, p.getEmail());
System.out.println("Person " + p + "added");
}

/**
* Find the person stored in the organizer with the email address.
* Note, each person will have a unique email address.
*
* @param email The person email address you are looking for.
*
*/
public Person findByEmail(String email)
{
Person aPerson = staff.get(email);
return aPerson;
}

private Map<Person, String> staff = new HashMap<Person, String>();

public static void main(String[] args)
{
OrganizeThis testObj = new OrganizeThis();
Person person1 = new Person("J", "W", "111-222-3333", "JW@ucsd.edu");
testObj.add(person1);

System.out.println(testObj.findByEmail("JW@ucsd.edu"));
}
}

最佳答案

您做错的事情是您以相反的顺序插入键和值(假设您希望电子邮件作为键)。你可以在docs中看到put 的签名采用 (key, value)

改变

staff.put(p, p.getEmail());

staff.put(p.getEmail(), p);

private Map<Person, String> staff = new HashMap<Person, String>();

private Map<String, Person> staff = new HashMap<String, Person>();

现在您将能够通过电子邮件地址查找人员

关于java - 关于 Java 中的 Hashmap 的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2831767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com