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);
}
}
}
The above code is for a basic mail server. I was attempting to make it store a MailItem(String recipient, String subject, String message) in a HashMap with a String key and an ArrayList (of MailItems) value.
What I am having trouble with is the post() method. I can't figure out how to make it take the parameter of who the message is intended for and store it in the corresponding ArrayList.
I am also having problems with the getNextMailItems() method. I can't figure out how to make it return multiple items from the ArrayList of the recipient. All I have been able to figure out is to add a parameter specifying how many MailItems to return.
I am incredibly inexperienced with java and am still learning. Please help. Thank you all.