【问题标题】:Google Guava MultiMap I don't know how to get access to my objectsGoogle Guava MultiMap 我不知道如何访问我的对象
【发布时间】:2017-01-29 18:44:46
【问题描述】:

我创建了一个 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());
        ???????
    }
}

【问题讨论】:

  • 所以你认为这个类存在;并且您阅读了有关如何插入内容的文档,但您无法阅读有关检索值的文档?只是想知道......

标签: java collections guava


【解决方案1】:

Guava 的 Multimap 为每个键保留一个 Collection 值。 因此,您的第二个迭代器 iterator2 返回的 Object 实际上是您之前输入的 Student

也许使用适当的泛型更有意义,即将您的Multimap 声明为Multimap&lt;Integer, Student&gt;。然后您的第二个迭代器将返回 Student 而不是 Object

【讨论】:

    猜你喜欢
    • 2010-10-15
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 2015-04-30
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多