4

我最近在工作中遇到了一些代码(重新创建为类似于我正在处理的代码)类似于下面的代码

有没有办法可以修改下面的代码以使用一个数据结构(考虑到性能)?

这是一些代码来说明我的意思:

public class ObjectMapper {

    private Map<UUID,Integer> uuidMap;
    private Map<Integer,UUID> indexMap;

    public ObjectMapper(){
        uuidMap = new HashMap<UUID,Integer>();
        indexMap = new HashMap<Integer,UUID>();
    }

    public void addMapping(int index, UUID uuid){
        uuidMap.put(uuid, index);
        indexMap.put(index, uuid);
    }


    .
    .
    .

    public Integer getIndexByUUID(UUID uuid){
        return uuidMap.get(uuid);
    }

    public UUID getUUIDByIndex(Integer index){
        return indexMap.get(index);
    }


}
4

4 回答 4

5

此处建议使用Google Collections中的 BiMap 来回答此问题

于 2009-05-13T22:57:07.387 回答
2

Apache 集合支持BidiMap接口和各种相当有效的实现。

于 2009-05-13T23:19:58.613 回答
1

您可以使用一个Map<Object,Object>来完成两个映射。丑,当然。ObjectMapper性能应该大致相同,或者在您有很多映射值很少的情况下稍好一些。

于 2009-05-13T23:06:31.863 回答
1

您可以使用Eclipse Collections中的BiMap

BiMap是一个允许用户从两个方向执行查找的地图。BiMap 中的键和值都是唯一的。

主要实现是HashBiMap.

inverse()

BiMap.inverse()返回一个视图,其中键类型和值类型的位置被交换。

MutableBiMap<Integer, String> biMap =
  HashBiMap.newWithKeysValues(1, "1", 2, "2", 3, "3");
MutableBiMap<String, Integer> inverse = biMap.inverse();
Assert.assertEquals("1", biMap.get(1));
Assert.assertEquals(1, inverse.get("1"));
Assert.assertTrue(inverse.containsKey("3"));
Assert.assertEquals(2, inverse.put("2", 4));

put()

MutableBiMap.put()行为类似于Map.put()在常规地图上,除了在添加重复值时抛出。

MutableBiMap<Integer, String> biMap = HashBiMap.newMap();
biMap.put(1, "1"); // behaves like a regular put()
biMap.put(1, "1"); // no effect
biMap.put(2, "1"); // throws IllegalArgumentException

forcePut()

其行为类似于MutableBiMap.put(),但在将键值对放入映射之前,它会默默地删除具有相同值的映射条目。

MutableBiMap<Integer, String> biMap = HashBiMap.newMap();
biMap.forcePut(1, "1"); // behaves like a regular put()
biMap.forcePut(1, "1"); // no effect
biMap.forcePut(1, "2"); // replaces the [1,"1"] pair with [1, "2"]
biMap.put(2, "2"); // removes the [1, "2"] pair before putting
Assert.assertFalse(biMap.containsKey(1));
Assert.assertEquals(HashBiMap.newWithKeysValues(2, "1"), biMap);

注意:我是 Eclipse 集合的提交者。

于 2013-12-21T18:55:32.493 回答