Only interesting, why method hashCode() in java.lang.String is not static? And in case of null return e.g. -1 ? Because frequently need do somethihg like:
String s;
.............
if (s==null) {
return 0;}
else {
return s.hashCode();
}
Thanks.
As others have noted hashCode
is a method on Object
and is non-static because it inherently relies (i.e. belongs to) an object/instance.
Note that Java 7 introduced the Objects
class, which has the hashCode(Object)
method, which does exactly what you want: return o.hashCode()
if o
is non-null or 0
otherwise.
This class also has other methods that deal with possibly-null
values, such as equals(Object, Object)
, toString(Object)
and a few others.
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