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

有没有办法可以重新编写下面的代码以使用一种数据结构(考虑到性能)?

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

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


}
有帮助吗?

解决方案

其他提示

您可以使用单个Map<Object,Object>做到既映射。丑陋的,肯定的。性能应该是大致相同的,或在万一你有几个映射值很多ObjectMappers略胜一筹。

您可以使用 双图日食系列.

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 集合的提交者。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top