【发布时间】:2014-04-14 11:37:06
【问题描述】:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Iterator;
import java.util.Map;
import java.util.AbstractMap;
/**
* A simple model of a mail server. The server is able to receive
* mail items for storage, and deliver them to clients on demand.
*/
public class MailServer
{
// Storage for the arbitrary number of mail items to be stored
// on the server.
private HashMap<String,ArrayList<MailItem>> mailMap;
/**
* Constructor
*/
public MailServer()
{
mailMap = new HashMap<String,ArrayList<MailItem>>();
}
/**
* Return how many mail items are waiting for a user.
*/
public int howManyMailItems(String who)
{
int count = 0;
for(ArrayList<MailItem> array : mailMap.values()) {
for (MailItem item : array) {
if (item.getTo().equals(who)) {
count++;
}
}
}
return count;
}
// public int howManyMailItems(String who)
// {
// return mailMap.get(who).size();
// }
/**
* Return the next mail item for a user or null if there
* are none.
*/
public MailItem getNextMailItems(String who, int howMany)
{
// Access the ArrayList for "who" remove and return the first element
// Be careful what if "who" doesn't have an entry in the mailMap
// Or what if "who" doesn't have any mail?
Iterator<Map.Entry<String, ArrayList<MailItem>>> it =
mailMap.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<String, ArrayList<MailItem>> entry = it.next();
String key = entry.getKey();
ArrayList<MailItem> value = entry.getValue();
if (key.equals(who));
{
return value.remove(0);
}
}
return null;
}
/**
* Add the given mail item to the message list.
*/
public void post(String who)
{
if (mailMap.containsKey(who)) {
Map.put(who, Map.get(who) + 1);
}
}
}
上面的代码是一个基本的邮件服务器。我试图让它在 HashMap 中存储一个 MailItem(String recipient, String subject, String message),其中包含一个 String 键和一个 ArrayList (of MailItems) 值。
我遇到的问题是 post() 方法。我不知道如何让它接受消息的目标参数并将其存储在相应的 ArrayList 中。
我的 getNextMailItems() 方法也有问题。我不知道如何让它从收件人的 ArrayList 中返回多个项目。我所能想出的只是添加一个参数,指定要返回多少 MailItems。
我对 Java 非常缺乏经验,并且仍在学习。请帮忙。谢谢大家。
【问题讨论】:
-
我建议查看 Guava Multimap,它用更直观、更强大的实现替换了列表映射。
-
我正在做的项目需要一个带有 ArrayList 的 HashMap
-
是的,但我不想作弊。我现在没有任何可用的帮助。有人建议我将堆栈溢出作为寻求帮助的好方法。
标签: java arraylist hashmap store