I have a StringIntTable
based on a HashMap<String, Integer>
.
It's with a single purpose: to produce as a perfect min hash for distinct Strings (each String will have a unique int associated).
Implementation is simple as demonstrated in the code, by extending HashMap<String, Integer>
and a special put
method to produce unique integer for each String. In the end the class will have a String -> int hash
mapping and I can easily query the hash value given a String by stringIntTable.get("stringValue")
.
However, my concern is that it will work only if callers are only calling the special put(final String string)
method to add values in. If they call parent HashMap
functions like put(K key, V value)
or putAll
, it would beat the purpose.
Therefore, I'm wondering if there's a way for me to restrict StringIntTable
users to only call the put
method but not other similar HashMap
functions to put new values in?
public class StringIntTable extends HashMap<String, Integer> {
public int put(final String string) {
return super.computeIfAbsent(string, v -> super.size() + 1);
}
}
One way I can think of, is to use the adapter pattern.
The drawback being that I'll have to provide functions like lookup()
and size()
, which are readily available if using previous implementation.
public class StringIntTable {
private final HashMap<String> stringLookup = new HashMap<>();
public int put(final String string) {
return stringLookup.computeIfAbsent(string, v -> stringLookup.size() + 1);
}
// Have to write more functions
public int lookup(final String string) {
return stringLookup.get(string);
}
public int size() {
return stringLookup.size();
}
...
}
Aucun commentaire:
Enregistrer un commentaire