【问题标题】:Looping through Set containing Entry objects循环遍历包含 Entry 对象的 Set
【发布时间】:2016-08-06 08:11:24
【问题描述】:
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());
        }
     }
}

编译错误

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

我正在尝试为 Set 中的每个条目类型对象打印键值对。但它给出了上面显示的编译时错误。但是,如果我用“h.entrySet()”替换“s”并循环正常,代码可以正常工作。使用引用来保存“h.entrySet()”如何导致编译错误?

【问题讨论】:

    标签: hashmap entryset


    【解决方案1】:

    线

    Set s = h.entrySet();
    

    应该是

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

    因为对于下面的每个循环都不知道 Set 是什么类型的?

    此代码有效:

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

    每当你看到

    incompatible types: Object cannot be converted to.. error
    

    这意味着 JVM 试图将 Object 类型转换为其他类型并导致编译错误。这里发生在 for 循环中。

    【讨论】:

      猜你喜欢
      • 2010-12-07
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 2020-06-09
      相关资源
      最近更新 更多