4

I need to store a list of Strings and need to check if a String exists in the list.

I normally would just use some Map with a key and boolean... i.e.

HashMap map<String,Boolean> = new HashMap<String,Boolean)()

And just do a map.contains(string)

This is sort of the way I have always done these kind of lookups in the past because I know that using a map will be O(1) access.

I know this might be nitpicky and unimportant, but I was just curious if there was some structure that was out there that would save that boolean value. Just seems like a waste of memory because I don't care about the false value because if the key doesn't exist that equates to false.

I was thinking maybe pointing a keyword to null would do what I want, but I was wondering if there was some data structure that sort of did this.

K2xL
  • 9,730
  • 18
  • 64
  • 101

5 Answers5

5

This is what the Set<T> collection is for. The HashSet<T> implementation is O(1) and internally does just what you propose: It's a HashMap<T,V> where the value for each key is the same internal Object instance. That is, the source contains

// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

and the value of each entry is set to PRESENT.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
4

Maybe a HashSet<E>?

Or indeed, anything that implements Set<E>, although they don't all have O(1) expected lookup.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
0

HashSet (or) Someother Set interface implementation may get you the functionality you are looking for.

kosa
  • 65,990
  • 13
  • 130
  • 167
0

You should use HashSet<E> - "data structure to hold just keys (not caring about value)". Its implementation is based on HashMap<K,V>, where each element is a value, and keys are just Object, exactly what you need.

public class HashSet<E> ... {
    ...
    private transient HashMap<E,Object> map;

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();

    public HashSet() {
        map = new HashMap<E,Object>();
    }
    ...

    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

    ...
}
chicout
  • 937
  • 7
  • 16
-1

Why not use the usual ArrayList<String> it has the contain method and everything else...

Adel Boutros
  • 10,205
  • 7
  • 55
  • 89
  • that would make adding keywords to the list take a long time – K2xL Mar 02 '12 at 21:18
  • @K2xL - no, adding to the (unsorted) list is O(1), but the contains operation is O(n). – Andreas Dolk Mar 02 '12 at 21:22
  • @Andreas_D well i should've been more specific, but Arraylists have to reallocate when the size of their internal structure reaches its limits (and you add another item). But yes, the contains method would take O(n) – K2xL Mar 05 '12 at 19:21