繁体   English   中英

Map.Entry m =(Map.Entry)i.next();

[英]Map.Entry m = (Map.Entry)i.next();

为什么我需要在i.next();前面有(Map.Entry) i.next(); 为什么我不能只有Map.Entry m = i.next();

抱歉。 这是一个HashMap。

因为它显然不是Iterator<Map.Entry> 可能是Iterator<Object>Iterator<Map.Entry<String, String>>或其他名称。

例如下面的Map

Map<String, Object> map = new HashMap<String, Object>();

返回以下Iterator

Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();

依次将以下Map.Entry返回给next()

Map.Entry<String, Object> entry = iterator.next();

因为您没有正确使用泛型(我知道一遍又一遍地键入所有内容很麻烦,但这是值得的),当它们放在一起时,他们会为您做(将其转换为Map.Entry)

HashMap<String, YourClass> map;
Iterator<Map.entry<String, YourClass>> it = map.entrySet().iterator();
while(it.hasNext()){
    Map.entry<String, YourClass> entry = it.next();//see no explicit cast
    //use entry
}

作为最终提示复制粘贴(和不错的IDE)是使用泛型的最大朋友

这有点大胆的猜测,因为您尚未发布任何代码或未声明要使用的Java版本,但是我猜测:

  • 您习惯使用泛型的Java(≥1.5)代码,例如HashMap<K, V>
  • 现在,您正在维护一个不使用泛型的,为Java 1.4或更早版本编写的代码库。

例如,您可能知道HashMap具有String键和Integer值,但这不能反映在HashMap的类型中,因此您必须强制转换单个值。

使用泛型:

HashMap<String, Integer> map;

// ...

int sum = 0;
for (Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator();
     it.hasNext;
     ) {
    Map.Entry<String, Integer> e = it.next();
    Integer value = e.getValue();
    sum += value.intValue();
}

没有泛型:

HashMap map;

// ...

int sum = 0;
for (Iterator it = map.entrySet().iterator();
     it.hasNext;
     ) {
    Map.Entry e = (Map.Entry) it.next();
    Integer value = (Integer) e.getValue();
    sum += value.intValue();
}

如果无法使用泛型(或者您正在使用提供非泛型集合的旧式库),则只能选择使用这些强制类型转换。
BTW:即使有仿制药,这些强制类型转换仍在引擎罩由编译器应用。

注意:省略了foreach循环和自动拆箱,因为这些在Java 1.4和更早版本中也不可用。

因为当您不使用泛型时, i.next()返回对象,因此必须对其进行i.next()转换才能进行分配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM