在Java中帮助Hashmaps [英] Help with Hashmaps in Java

查看:78
本文介绍了在Java中帮助Hashmaps的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定我如何使用get()来获取我的信息。看着我的书,他们通过密钥得到()。我认为get()返回与该文档关联的对象。但是我一定在这里做错了什么......任何想法?

I'm not sure how I use get() to get my information. Looking at my book, they pass the key to get(). I thought that get() returns the object associated with that key looking at the documentation. But I must be doing something wrong here.... Any thoughts?

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)

The thing you are doing wrong is that you are inserting the key and value in reverse order (assuming you want email to be the key). You can see in the docs that the signature for put takes (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>();

现在您可以查找 Person 通过其电子邮件地址。

Now you will be able to look up a Person by its email address.

这篇关于在Java中帮助Hashmaps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆