开发者

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

Why do I need to have (Map.Entry) in front of the i开发者_开发问答.next(); ? Why can't I have just Map.Entry m = i.next();?

Sorry. It is a HashMap.


Because it's apparently not an Iterator<Map.Entry>. Maybe it's an Iterator<Object>, or an Iterator<Map.Entry<String, String>> or something different.

For example, the following Map

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

gives the following Iterator back

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

which in turn gives the following Map.Entry back on next()

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


because you are not using the generics correctly (it's a hassle I know to type out everything over and over and over but it's worth it) they will do that (the casting to Map.Entry) for you when it all comes together

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
}

as a final hint copy paste (and a decent IDE) is your greatest friend with generics


This is a bit of a wild guess because you haven't posted any code or stated which version of Java you are using, but I am guessing that:

  • You are used to Java (≥1.5) code that uses generics, e.g. HashMap<K, V>
  • You are now maintaining a codebase written for Java 1.4 or earlier that does not use generics.

e.g. you may know that a HashMap has String keys and Integer values, but this cannot be reflected in the type of the HashMap, so you must cast individual values.

With generics:

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();
}

Without generics:

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();
}

If generics are unavailable (or you are working with a legacy library that gives you non-generic collections) you have no choice but to apply these casts.
BTW: Even if you do have generics, these casts are still applied under-the-hood by the compiler.

Note: leaving out foreach loops and auto-unboxing as these are also unavailable in Java 1.4 and earlier.


Because i.next() returns object when you don't use generics and you have to cast it to be able to assign it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜