tags:

views:

229

answers:

3

I ran across some code recently at work (recreated to be similar to what I am dealing with) similar to the code below

Is there a way I can rework the code below to use one data structure (with performance in mind)?

Here is some code to illustrate what I mean:

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


}
+3  A: 

This is answered here with the recommendation to use BitMap from Google Collections

Yishai
Cool. I was really hoping for a way to do this without bringing in an outside Jar, though. But that may not be possible.
Grasper
If you look at BiMap's code, they use the double map to implement it, so I would say that it is the most obvious implementation, anyway. http://google-collections.googlecode.com/svn/trunk/src/com/google/common/collect/StandardBiMap.java
Yishai
A: 

You could use a single Map<Object,Object> to do both mappings. Ugly, sure. Performance should be roughly the same, or slightly better in the unlikely event that you have many ObjectMappers with few mapped values.

Tom Hawtin - tackline
A: 

Apache collections supports a BidiMap interface and a variety of fairly effective implementations.

Uri