I have a function which returns an int
value for a given key (from a HashMap<String, Integer>
). If the key doesn't exist, I want to return something the caller can check for. It seems that, most commonly, this would be a "returns -1 if key doesn't exist" kind of thing. However, I can't reserve -1 for that purpose in my case, because negative numbers are feasible values for keys which do exist.
The only other options I have been able to come up with are the following:
Integer
wrapper class and check for null
Integer.MIN_VALUE
boolean keyExists(String key)
function which should always be called firstfloat
and use NaN
insteadI am writing this in Java, but people from similar language backgrounds are welcome to post. Thanks!
The first option is, in my opinion, the cleanest. Magic numbers like -1 and Integer.MIN_VALUE are kind of messy, especially when the values aren't intuitive. That is an idiomatic C solution, which Java developers will hate you for. Depending on what you're actually using this for you could also throw a "KeyNotFoundException" if this only happens in "exceptional" circumstances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With