The original code was supplied and we modified it as part of an assignment to add a hashmap and a print method, etc. I seem to have most of it working, but am having problems with the printMessages method.
If there are no messages, I get a null pointer exception despite the if statement that should solve that. If there are messages, It works fine, except the message comes out as gibberish even though I called toString on it. Can anyone see the problems in the code?
import java.util.ArrayList;
import java.util.Iterator;
import java.util.HashMap;
/**
*
*/
public class MailServer
{
//HashMap using generics
private HashMap <
String, ArrayList><MailItem>> messages;
/**
* construct MailServer and initialize HashMap
*/
public MailServer()
{
messages = new HashMap<String, ArrayList><MailItem>>();
}
/**
* return messages by user name
* @param name is user request is made for
* if no messages, return null
*/
public MailItem getNextMailItem(String name)
{
ArrayList<MailItem> lists = messages.get(name);
if (lists == null) {
return null;
}
Iterator<MailItem> it = lists.iterator();
while(it.hasNext()) {
MailItem mess = it.next();
it.remove();
return mess;
}
return null;
}
/**
* filter spam if message subject starts with "spam" or has "viagra" in subject
* */
public void post(MailItem item)
{
String name = item.getTo();
//filter spam
if (item.getSubject().toLowerCase().startsWith("spam") || item.getMessage().toLowerCase().contains("viagra")) {
return;
}
if (! messages.containsKey(name)) {
messages.put(name, new ArrayList<MailItem>());
}
messages.get(name).add (item);
}
public void printMessages(String name)
{
ArrayList<MailItem> lists = messages.get(name);
if (lists == null) {
System.out.println("No messages");
}
else
{
Iterator<MailItem> it = lists.iterator();
while(it.hasNext())
{
MailItem mess = (MailItem)it.next();
System.out.println("Messages for: " + name);
System.out.println(mess.toString());
}
}
}
}