Java string hashCode empty string

Just wondering why the hashCode () method in java.lang.String is not static? And in the case of zero return, for example. -one? Because often you need to do something like:

String s; ............. if (s==null) { return 0;} else { return s.hashCode(); } 

Thanks.

+4
java string null static
source share
5 answers

As others have noted, hashCode is a method on Object and is non-stationary, because it essentially relies on (i.e. belongs to) an object / instance.

Note that Java 7 introduces an Objects class that has hashCode(Object) that does exactly what you want: return o.hashCode() if o not null or 0 otherwise.

This class also has other methods that deal with possible null values, such as equals(Object, Object) , toString(Object) and several others.

+14
source share

because if it were static "1".hashCode() and "2".hashCode() , it would return the same value, which is obviously incorrect.

It is specific to each instance and depends on it, so it cannot be static.

+7
source share

Since String hash is a property of this string.

With the same thought, you can make each method static.

+2
source share

hashCode used to obtain the hash code of the object, in order to know in which HashMap bucket this object should be placed. Thus, it must be an instance method of an object and it must be called polymorphic.

null can be used as a key in HashMap, but it is considered as a special case.

It seems you are using hashCode for another purpose, so you have to handle a specific path.

+2
source share

Its returning hashCode Object not a class.

+1
source share

All Articles