Data Class包含两个字段price(double),operator(string),我将Data类作为多个值映射到下面显示的地图的每个键为1)。
我无法在代码2中显示。在同一个键下映射的所有值
示例,对于Key = 1,map的值为Price {0.2,0.3,0.4},运算符:{A,B,C}
此代码的输出,只能显示价格= 0.2,运算符:A代表键1.所有其他值均未显示。怎么解决呢?
1) Map<Integer, ArrayList<Data>> mp = new HashMap<Integer, ArrayList <SortData>>();
2)
ArrayList<Data> ls = mp.get (keys.get(k));
int i=0;
for ( Data e: ls)
{
System.out.println(e.getOperator() + e.getPrice());
i++;
}
在地图中添加数据的代码:
enter code here
ArrayList<Test> list = new ArrayList<Test>();
Map<Integer,ArrayList<Test>> mp = new HashMap<Integer,ArrayList<Test>>();
list.add(new Data(0,1,"A"));
list.add(new Data(0,2,"B"));
mp.put(1,list);
List<Test> value = mp.get(1);
value.add(0.3,"c");
value.add(0,5,"E");
答案 0 :(得分:1)
在用于向地图添加值的代码中 - 编译错误。您无法将数据对象添加到ArrayList。
您的迭代代码是正确的。所以我相信这些价值在地图中根本就不存在。因此,请检查所有代码,从列表中删除值。并确保在添加值代码中将值添加到存储在Map中的同一实例中。
尽管如此,为了减少错误电话代码,请考虑使用Guava MultiMap