Collection with index and hash access

I need a collection class that has both fast and hash access. Now I have an ArrayList. It has good access indexes, but its method containsdoes not work. HashSet has a good implementation contains, but not indexed acces. Which collection has both? Probably something from Apache? Or should I create my own collection class that has: ArrayList for indexed acces and HashSet for containscheck?

Just to clarify: I need both get(int index), andcontains(Object o)

+5
source share
4 answers

If indexed access performance is not a problem, the closest match is a LinkedHashSet, whose API says it

A hash table and associated list of the Set interface, with a predictable iteration order.

At least I don’t think that performance will be worse than LinkedListPerformance. Otherwise, I see no alternative but your solution ArrayList + HashTable

+1
source

If you look at the index from start to finish, I think it can satisfy your needs: LinkedHashSet

If you need random access via an index, as well as access to a hash, if someone else does not have a better offer, I think you can make your own collection that does both.

0
source

; , , :)

class DataStructure<Integer>{
   Hash<Integer,Integer> hash = new HashMap<Integer, Integer>();
   List<Integer> list = new ArrayList<Integer>();

    public void add(Integer i){
        hash.add(i,i);
        list.add(i);
    }
    public Integer get(int index){
        return list.get(index);
    }
   ...
} //used Integers to make it simpler

, ; HashMap/HashSet, ArrayList.

,

 contains method : call hashed contains method.

 get an object with index: use array to return the value

, . / .

0

, , , . map.put(objectHash, obj).

, :

boolean contained = map.containsValue(obj);

:

MyObject object = map.get(objectHash);

, , , .

0

All Articles