我正在处理电子邮件客户端的垃圾邮件过滤器项目。
public MailServer()
{
mailMap = new HashMap<String,ArrayList<MailItem>>();
}
我被指示使用HashMap存储收件人和ArrayLists来保存他们的mailItems。下一个方法是计算并返回特定收件人的mailItems。
public int howManyMailItems(String who)
{
int count = 0;
for(MailItem item : mailMap) {
if(item.getTo().equals(who)) {
count++;
}
}
return count;
}
修改
我在BlueJ工作,当我尝试编译该类时,它会在第4行突出显示mailMap并说
“for-each loop not cicable”
public int howManyMailItems(String who)
{
int count = 0;
for(MailItem item : mailMap.keySet()) {
if(item.getTo().equals(who)) {
count++;
}
}
return count;
}
当我尝试使用keySet时,它会说不兼容的类型。
答案 0 :(得分:2)
Map
未实现Iterable
接口。这就是为什么你得到“for-each loop not appicable”错误。您可以选择迭代地图的
entrySet()
- Set<Map.Entry<K,V>>
(其中K
是密钥类型,V
是地图的值类型); keySet()
- Set<K>
;或values()
- Collection<V>
。一般来说,你会想做这样的事情:
public int howManyMailItems(String who)
{
int count = 0;
for(Map.Entry<String,ArrayList<MailItem>> entry : mailMap.entrySet()) {
String key = entry.getKey();
ArrayList<MailItem> array = entry.getValue();
// process key and array value
}
return count;
}
很难确切地告诉您使用什么逻辑来计算。如果您只需要数组(并忽略地图的键),那么您可以使用:
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;
}
P.S。通常认为使用接口而不是具体类型声明泛型参数类型是一种好习惯。例如,您的地图可以声明:
Map<String, List<MailItem>>
而不是
Map<String, ArrayList<MailItem>>
(您必须相应地修改迭代循环中使用的类型。)您仍然可以将ArrayList
的实例放入地图中,但您也可以改变主意并添加其他类型{{1} }。 (例如,您可以将调用后的不可修改列表放入List
。)
答案 1 :(得分:0)
public int howManyMailItems(String who) {
return mailMap.get(who).size();
}
答案 2 :(得分:0)
你没有提到任何错误,所以很难知道什么是错的,但通常你会遍历通过keySet()
获得的Map的密钥集,或通过values()
获得的值。< / p>
即,
for(String key : mailMap.keySet()) {
List<MainItem> itemList = mailMap.get(key);
count += itemList.size(); // ??? not sure if this is what you want??
// ... etc..
}
答案 3 :(得分:0)
正如你HashMap<String,ArrayList<MailItem>>
。关键是String
的类型,值为ArrayList<MailItem>
。您输入错误的原因是您获取List并尝试将其分配给MaiItem。
public int howManyMailItems(String who)
{
int count = 0;
if(who == null) { //Check the input before operate
return count;
}
for(Iterable<MailItem> iterable : mailMap.values()) { //Interface instead of Class
for (MailItem item : iterable) {
if (item == null) { //It is possible that item can be null
continue;
}
if (who.equals(item.getTo())) { //It is possible that To can be null
count++;
}
}
}
return count;
}
为什么在for-each循环中使用Iterable而不是ArrayList?
该解决方案的优点在于,我们不必更改我们决定使用另一个Collection
存储的代码。
为什么Iterable不是收藏?
在这种情况下,我们只执行读取操作,因此这是解决任务所需的最小值。这样做的好处是更大的代码灵活性。