I want to implement a collection (a bit like a map but for single values rather than pairs) that performs a hash when searching its contents. I’m trying to make my programs really effcient. Currently the program uses a HashMap and adds the primary key from a database to it twice:
HashMap<Long, Long> userKeys = new HashMap<Long, Long>();
Some operations
userKeys.add(key, key);
Is there a Hash or Map I can use to avoid adding the key twice? As it’s a primary key in a database I know there are going to be no duplicates and hence the reason I thought of a hash to be efficient.
I thought a Vector might be a good choice but when I looked at the contains() method it goes through every entry which is going to be very inefficient in this case.
I’ve also had a look at HashSet’s but unfortunately from what I’ve seen there’s no method for extracting values so that they can be used, unlike the HashMaps.get(Object) method.
Desired set up:
Collection<Long> userKeys = new Collection<Long>();
Some operations
userKeys.add(key);
Desired operations:
userKeys.contains(key) <- Uses hash here
userKeys.get(index)
I think
HashSetis what you should be using – if you don’t really have a key/value relationship, it should be all you need. You can get at the values by iterating over the set.It’s not clear what your
get(index)is meant to return… what’s the index here?If you need to preserve insertion order, you could use
LinkedHashSet.If you need to preserve insertion order and have random access by insertion order (i.e. get the third entry you added via
get(2)) then you could keep aHashSetand anArrayList, keeping the two in sync yourself. (Encapsulate them in a separate type.) Use theHashSetfor containment tests, and theArrayListfor random access.