Since you are learning Java, let me point out a few things:
Please try the Guava
MultiMap
instead of the much uglier:private HashMap<String,ArrayList<MailItem>> mailMap;
Also try to use interfaces instead of classes, i.e.,
Map<String,List<MailItem>
would be better because it does not tie you to the particular implementation.This is not optimal and I suspect wrong:
int count = 0; for(ArrayList<MailItem> array : mailMap.values()) { for (MailItem item : array) { if (item.getTo().equals(who)) { count++; } } }
you should call
get(who)
on the map and if you get a non null list, you will have a list ofMailItem
s forwho
. Then callingList.size()
will give you the count (I suspect) you need.Two notes about this block of code:
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)); // the semicolon here means that if the condition is true, do nothing { return value.remove(0); // this block is ALWAYS EXECUTED } } return null;
If the condition in the if is true, nothing will be executed because of the semicolon and the code in the code block will always be executed the first time. That said, once again you are given the key, so you don't need to loop through the whole map (see previous point). However, if you want to iterate a map please use the more compact idiom:
for(Map.Entry<String,ArrayList<MailItem>> e : mailMap.entrySet()){ // do something with the key and value, e.getKey(), e.getValue() }
Finally, this block is puzzling:
if (mailMap.containsKey(who)) { Map.put(who, Map.get(who) + 1); }
what are you trying to do? Map is the name of an interface and doesn't have static methods
put
orget
so that won't even compile. If you were trying to add an element tomailMap
for the keywho
then you probably want something like (typical idiom for map of lists, again see Guava for a better API):ArrayList<MailItem> l = mailMap.get(who); if(l == null){ // this super verbose code will simplify with the Guava MultiMap l = new ArrayList<MailItem>(); mailMap.put(who, l); } l.add(/* code to create a new MailItem */);