【问题标题】:using Guava BiMap in Java在 Java 中使用 Guava BiMap
【发布时间】:2018-12-13 23:12:57
【问题描述】:

这是我第一次使用这个库。

为了解释我的问题,让我们举个小例子:

package javaapplication7;


import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;


public class JavaApplication7 {
public static void main(String[] args) {
    BiMap<Integer, Integer> biMap = HashBiMap.create();

    biMap.put(0, 0);
    biMap.put(2, 1);
    biMap.inverse().put(1,3);

    System.out.println(biMap.get(0));
    System.out.println(biMap.get(2));
    System.out.println(biMap.inverse().get(1));

    }

}

这个程序的结果是:

0

3

通常第二次打印我应该得到 1 ,有人可以向我解释为什么我得到一个空值吗?

在我的程序中,我应该在地图中放一些整数,没有特定的顺序,我该怎么做?

我想得到前面例子的 0 1 3 结果。

谢谢。

【问题讨论】:

    标签: java dictionary collections guava


    【解决方案1】:

    通过将 key 1 插入 inversed bimap 视图,您实际上覆盖了您之前映射的 value 1(即在“正常”biMap 中不再有键 2,但在 3 下有值 1)。每次操作后看看你的biMap 发生了什么:

    biMap.put(0, 0);
    System.out.println(biMap); // {0=0}
    biMap.put(2, 1);
    System.out.println(biMap); // {0=0, 2=1}
    final Integer previousValue = biMap.inverse().put(1, 3);
    System.out.println(biMap); // {0=0, 3=1}
    System.out.println(previousValue); // 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多