Issue
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();
}
...
}
Solution
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.
You have already answered your own question, just replace #lookup()
with #get()
.
Also, that's not the only way to do this.
All you have to do is either re-write more code, or write more methods.
One way is your Adapter
-> write more methods.
The other way is to reimplement/override the functions from HashMap.class
. -> re-write more code.
I'd rather write more methods than re-write pre-existing code.
If you would like to re-write more code, you have to override (not overload) or rewrite the whole class itself.
Answered By - JumperBot_
Answer Checked By - Senaida (JavaFixing Volunteer)