【问题标题】:How to correct the compiler error saying incompatible types?如何纠正编译器错误说不兼容的类型?
【发布时间】:2020-02-25 19:10:51
【问题描述】:
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
    int[] arr= {1,2,1,1,2,3};
        HashMap <Integer,ArrayList<Integer>> hm= new HashMap<Integer,ArrayList<Integer>>();
        for(int i=0;i<arr.length;i++)
        {
            if(hm.get(arr[i])==null)
            {
                hm.put(arr[i],new ArrayList<Integer>());
                hm.get(arr[i]).add(i);
            }
            else
                hm.get(arr[i]).add(i);
        }
        int[] res= new int[6];
        for(Map.Entry m:hm.entrySet())
        {
            ArrayList<Integer> p=m.getValue();
            for(int i=0;i<p.size();i++)
            {
                int s=0;
                for(int j=0;j<p.size();j++)
                {
                    if(i!=j)
                        s=s+Math.abs(p.get(i)-p.get(j));
                }
                res[p.get(i)]=s;
            }
        }
        for(int i=0;i<res.length;i++)
            System.out.print(res[i]+" ");
    }
}

编译器报错:

Main.java:28:错误:不兼容的类型:对象无法转换为 ArrayList ArrayList p=m.getValue(); ^ 1 个错误

为什么会显示不兼容的类型?

【问题讨论】:

  • 您的Map.Entry 是原始的。您应该为其添加适当的类型。

标签: java arraylist hashmap


【解决方案1】:

您没有指定迭代器的类型。变化:

for(Map.Entry m:hm.entrySet())

到:

for(Map.Entry<Integer,ArrayList<Integer>> m:hm.entrySet())

【讨论】:

  • ...为了便于阅读,也可以在几个空格中添加
猜你喜欢
  • 1970-01-01
  • 2015-03-27
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
  • 2011-04-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
相关资源
最近更新 更多