Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am getting the following error message in BlueJ for me code and I can not figu

ID: 3551866 • Letter: I

Question

I am getting the following error message in BlueJ for me code and I can not figure out why. I DO want to use a HAshMAp instead of an ArrayList:

"for-each loop not applicable to expression type

required: array or java.lang.iterable; found: java.util.HashMap<java.lang.String,java.util.ArrayList<MailItem>>"



public MailServer()

{

mailMap = new HashMap<String,ArrayList<MailItem>>();

}

/**

* Return how many mail items are waiting for a user.

* @param who The user to check for.

* @return How many items are waiting.

*/

public int howManyMailItems(String who)

{

// should be easy! Just find out the size of

// "who"'s ArrayList

// Be Careful! What if "who" doesn't have an entry

// in the mailMap?

int count = 0;

for(MailItem mail : mailMap) {

if(mail.getTo().equals(who)) {

count++;

}

}

return count;

}

Explanation / Answer

You can use for each loop over the the items which extends the iterable interface and HashMap is not one of them. Maps were introduced to get values from any location of a data structure with the use of some user friendly identifers and not to iterate over all the values present in them. If Maps would have implemented the Iterable interface it wold have defeated the purpose.


For your problem you can do certain things which may work depending on what you want.


for(MailItem mail : mailMap.get("your key(can be the user/who)")) {

count++;

}



If you need to count the no of users you can do this.


for(ArrayList<MailItem> mail : mailMap.values()) {

count++;

}


Alternatively you can use a nested for each loop like this


for(String mailKey : mailMap.keySet()) {

for(MailItem item: mailMap.get(mailKey)){

if(mail.getTo().equals(who)) {

count++;

}

}

}



Do let me know if you need clearance on any of the points.