Java中的Hashmaps帮助
我不确定如何使用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"));
}
}
# 1 楼答案
你做错的事情是,你正在以相反的顺序插入密钥和值(假设你希望电子邮件成为密钥)。您可以在docs中看到
put
的签名采用(key, value)
改变
到
及
到
现在,您可以通过电子邮件地址查找
Person
# 2 楼答案
下面是一个片段,展示了大多数
Map
功能: