Java迭代器类型转换为hashmap值 [英] Java iterator type casting in hashmap values

查看:92
本文介绍了Java迭代器类型转换为hashmap值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们需要在Java中输入caste Iterator?例如: -

Why do we need to type caste Iterator in Java? For example:-

HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
hm.put(1,3);
hm.put(2,6);
hm.put(3,7);
Iterator it = hm.values().iterator();
while(it.hasNext())
{
ans += it.next(); // Raises an error
}

但如果我更新我的错误代码:

But if I update my code to:

Iterator<Integer> it = hm.values().iterator();// works fine 

为什么迭代器没有将hm.values()类型转换为整数?



我尝试过:



在Java中迭代hashmap.values()

Why is iterator not type casting hm.values() to integer?

What I have tried:

Iterating over hashmap.values() in Java

推荐答案

Iterator 需要知道它要处理的对象,就像 HashMap 需要知道。如果未指定类型,则 Iterator 将在下一次调用时返回对象( ),然后需要转换为真实类型。
The Iterator needs to know what objects it is to deal with, in the same way that the HashMap needs to know. If the type is not specified then the Iterator returns an object on a call to next(), which then needs to be cast to its real type.


这篇关于Java迭代器类型转换为hashmap值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆