Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String hashCode of null string

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.

like image 522
user710818 Avatar asked Nov 27 '22 14:11

user710818


1 Answers

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.

like image 196
Joachim Sauer Avatar answered Dec 19 '22 12:12

Joachim Sauer