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);
}
}
}以上代码用于基本邮件服务器。我试图让它将一个MailItem(字符串收件人、字符串主题、字符串消息)存储在一个HashMap中,其中包含一个字符串键和一个ArrayList (of MailItems)值。
我遇到麻烦的是post()方法。我不知道如何使它接受消息的对象参数,并将其存储在相应的ArrayList中。
我还遇到了getNextMailItems()方法的问题。我不知道如何使它从收件人的ArrayList返回多个项目。我所能知道的就是添加一个参数,指定返回多少个MailItems。
我对java非常缺乏经验,而且还在学习。请帮帮忙。谢谢你们所有人。
发布于 2014-03-11 03:53:08
既然您正在学习Java,请允许我指出以下几点:
MultiMap,而不是更丑的:
HashMap mailMap;
另外,尝试使用接口而不是类,也就是说,Map<String,List<MailItem>会更好,因为它没有将您与特定的实现联系在一起。get(who),如果您得到一个非空列表,您将得到一个用于who的MailItem的列表。然后打电话给List.size()会给你你需要的计数(我怀疑)。put或get,所以甚至不会编译。如果您试图为键mailMap添加一个元素,那么您可能想要类似于(列表映射的典型成语,请参见番石榴以获得更好的who ):
ArrayList l= mailMap.get(who);if(l == null){ //这段超冗长的代码将简化为:番石榴MultiMap l=新ArrayList();mailMap.put(who,l);}l.add(创建新MailItem */的/*代码);https://stackoverflow.com/questions/22315886
复制相似问题