简体   繁体   中英

Efficient data structure with two keys

I have an Android app in which I use a HashMap to store container objects. During the course of the App, the datastructure is accessed continuously.

However, about half the time, the reference used in not the Key in the map but another variable from the object so I end up looping over the structure again and again.

Is there an efficient way to have a datastructure indexed on two keys in Java ?

为什么不是两个具有不同键的映射,但两者都指向相同的值?

Manage two maps, where two sets of keys map to the same underlying set of objects. Wrap them in a class that has methods similar to a normal map, but internally searches on both keys, and synchronizes additions and deletions.

This is efficient because manipulations are (in the worst case) linearly proportionate to managing a single map.

You could use one map with both keys:

Map<Object, Person> personMap = new HashMap<Object, Person>()

Person person = ...
personMap.put(person.getName(), person)
personMap.put(person.getSSN(), person)

Then you can retrieve by the key. This of course assumes that there are no collisions in your key usage. If your two keys are different class types, then this is safe to do. If your keys are the same type (example String ), then you may not want to use the two maps solution.

Follow-up: This approach does suffer from losing type safety, but it only impacts put(K, V) and putAll(Map<? extends K, ? extends V>) , as get(Object) and containsKey(Object) always accepts Object.

So with this limitation I'd wrap this single map or go with the two map solution (also wrapped).

我创建了一个结合了两个变量的关键对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM