xmen-5
xmen-5

Reputation: 1916

using Guava BiMap in Java

it's my first time i will use this library.

to explain my problem let's take this tiny example:

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));

    }

}

the result of this program is :

0

null

3

Normally for the second print i should get 1 , could someone explain to me why i get a null value ?

In My program i should put some integer in the map without a specific order , how can i do that?

I want to get 0 1 3 result for the preceding example.

Thank you.

Upvotes: 0

Views: 616

Answers (1)

Grzegorz Rożniecki
Grzegorz Rożniecki

Reputation: 28045

By inserting a key 1 to an inversed bimap view you actually overwrote a value 1 you had mapped earlier (i.e. in "normal" biMap there's no key 2 anymore, but under 3 there's value 1). Just see what's happening your biMap after each operation:

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

Upvotes: 2

Related Questions