【发布时间】: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是原始的。您应该为其添加适当的类型。