Set set = hm.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
// me.getValue should point to an arraylist
Iterator<Student> it = (me.getValue()).iterator();
while (it.hasNext()) {
// some code
}
}
好吧,我尝试迭代 Arraylist,但由于某种原因它不起作用,编译器告诉我它找不到该符号。我知道 me.getValue() 应该指向一个对象,在这种情况下,键/值对的值部分是一个 Arraylist。那么,出了什么问题?
最佳答案
当你这样做时
Map.Entry me = (Map.Entry)i.next();
您正在创建一个无类型的 Map.Entry 实例,这就像做
Map.Entry<Object, Object> me = ...
然后,当你尝试这样做
Iterator<Student> it = (me.getValue()).iterator();
这相当于尝试做
ArrayList<Object> objects;
Strudent s = objects.get(0);
这显然是你做不到的。相反,您需要使用适当的类型实例化 Map.Entry 对象:
Map.Entry<YourKeyType, ArrayList<Student>> me =
(Map.Entry<YourKeyType, ArrayList<Student>>) i.next();
请注意,您可以避免那里的强制转换,并充分利用generic type safety ,通过将迭代器设为 Iterator<YourKeyType, ArrayList<Student>>
而不是将其声明为原始类型。
关于java - 迭代 arraylist 的 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25985679/