How to make LruCache only accept key?

439 Views Asked by At

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.

1

There are 1 best solutions below

0
On BEST ANSWER

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"));