我创建了一个hashmultimap 如何使用迭代器访问hashmultimap中的Student对象?
Multimap<Integer, Object> myMultimap2 = HashMultimap.create();
Student one = new Student("Bob","Any",35);
Student two = new Student("Tom","Johnson",22);
Student three = new Student("Yo","Zun",42);
myMultimap2.put(1,one);
myMultimap2.put(2,two);
myMultimap2.put(2,three);
Iterator<Integer> iterator = myMultimap2.keySet().iterator();
while (iterator.hasNext()){
int key = iterator.next();
System.out.println(key);
Collection collection = myMultimap2.get(key);
Iterator iterator2 = collection.iterator();
while (iterator2.hasNext()){
System.out.println(iterator2.next());
???????
}
}
答案 0 :(得分:1)
Guava&#39; Multimap
为每个密钥保留Collection
个值。
因此,您的第二个迭代器Object
返回的iterator2
实际上是您之前放置的Student
。
使用正确的泛型可能更有意义,即将Multimap
声明为Multimap<Integer, Student>
。然后你的第二个迭代器将返回Student
而不是Object
。