0

LruCache is a map, but I want to use LruCache to only cache strings, i.e. I want LruCache to work as a HashSet.

How should I define a LruCache class?

LruCache<String, Void> won't work, because when my code called lruCache.put("abc", null), NullPointerException was thrown.

Thanks.

Kai
  • 3,775
  • 10
  • 39
  • 54
  • 1
    Don't store `null`. Store something else, such as a `String`. – CommonsWare Aug 06 '13 at 17:55
  • OK. I think I have to define LruCache, and put the string as both key and value, e.g lruCache.put(stringToCache, StringToCache). – Kai Aug 06 '13 at 18:01

1 Answers1

1

The docs are pretty clear:

This class does not allow null to be used as a key or value. A return value of null from get(K), put(K, V) or remove(K) is unambiguous: the key was not in the cache.

You can define your own string wrapper class to use for values. You can have a special instance of it to represent null strings.

public class StringValue {
    public final String string;
    public StringValue(String s) {
        string = s;
    }
    public String toString() {
        return String.valueOf(string); // in case it's null
    }
    public String asString() {
        return string;
    }
    public static final StringValue NULL = new StringValue(null);
}

Then you can store a non-null null:

LruCache<String, StringValue> lruCache = new LruCache<String, StringValue>();
lruCache.put("abc", StringValue.NULL);
lruCache.put("def", new StringValue("something"));
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521