Search code examples
javaguava

How to handle collisions in guava table?


Assume that we have a MyBean class with simple int count field, and Guava table like this;

Table<Integer, Integer, MyBean> table; // we can instantiate like HashBasedTable.create();

I want to sum count fields, when i put a new MyBean object and this position has an existing MyBean object in table.

table.put(1, 1, new MyBean(1)); 
table.put(1, 1, new MyBean(2)); // so what will be going on ?

Actually this is a very simple case and I want to work on complex objects if they are in collision.


Solution

  • The Table behaves just like a Map, i.e., the second put overwrites the first. What you'd need is sort of Multimap. There's an issue for a Multitable already, vote for it.

    Currently, you can either use a

    Table<Integer, Integer, SomeCollection<MyBean>>
    

    or a

    Map<SomePair<Integer, Integer>, MyBean>
    

    I'd recommend the latter, as composing keys is way simpler than dealing with the "multi" stuff.


    If you're feeling really hacky today, you could even use

    Map<Long, MyBean>
    

    Just don't tell anybody it was me who proposed this. And encapsulate the hack properly, so you don't don't get bitten by some int to long automatic conversion somewhere.