简体   繁体   English

遍历包含Entry对象的Set

[英]Looping through Set containing Entry objects

import java.util.*;

public class HelloWorld{

     public static void main(String []args){
        HashMap<Integer,String> h = new HashMap<Integer,String>();
        h.put(100,"Hola");
        h.put(101,"Hello");
        h.put(102,"light");
        System.out.println(h); // {100=Hola, 101=Hello, 102=light}
        Set s = h.entrySet();
        System.out.println(s); // [100=Hola, 101=Hello, 102=light] 
        for(Map.Entry<Integer,String> ent : s)
        {
            System.out.println("Key=" + ent.getKey() + " Value=" + ent.getValue());
        }
     }
}

Compile error 编译错误

HelloWorld.java:13: error: incompatible types: Object cannot be converted to Entry<Integer,String>                                                                                         
        for(Map.Entry<Integer,String> ent : s)                                                                                                                                             
                                            ^ 

I am trying to print key-value pair for each entry type object in the Set s. 我正在尝试为Set中的每个条目类型对象打印键值对。 But it gives compile time error shown above. 但是它给出了上面显示的编译时错误。 But code works fine if I replace "s" with " h.entrySet()" and loops fine..How does using reference to hold "h.entrySet()" cause compile error ? 但是,如果我将“ s”替换为“ h.entrySet()”并循环正常,则代码可以正常工作。使用引用持有“ h.entrySet()”如何导致编译错误?

The line 线

Set s = h.entrySet();

should be 应该

 Set<Map.Entry<Integer,String>> s = h.entrySet();

because for each loop below doesn't know what type of Set s is ? 因为下面的每个循环都不知道Set的类型是什么?

This code works: 此代码有效:

import java.util.*;

public class HelloWorld{

     public static void main(String []args){
        HashMap<Integer,String> h = new HashMap<Integer,String>();
        h.put(100,"Hola");
        h.put(101,"Hello");
        h.put(102,"light");
        System.out.println(h); // {100=Hola, 101=Hello, 102=light}
        Set<Map.Entry<Integer,String>> s = h.entrySet();
        System.out.println(s); // [100=Hola, 101=Hello, 102=light] 
         for(Map.Entry<Integer,String> ent : s)
        {
            System.out.println("Key=" + ent.getKey() + " Value=" + ent.getValue());
        }
     }
}

Whenever you see 每当你看到

incompatible types: Object cannot be converted to.. error

it means JVM is trying to covert Object type to some other type and it leads to compilation error . 这意味着JVM试图将对象类型转换为其他类型,这会导致编译错误。 Here it's happening in the for loop. 这是在for循环中发生的。

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

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