Java String hashCode of null string

2019-06-24 07:04发布

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.

5条回答
手持菜刀,她持情操
2楼-- · 2019-06-24 07:40

Because the hash code of a String is a property of that String.

With the same train of thought you could make every method static.

查看更多
男人必须洒脱
3楼-- · 2019-06-24 07:52

hashCode is used to get the hashCode of an object, in order to know in which bucket of a HashMap this object must be placed. It thus has to be an instance method of the object, and it must be called polymorphically.

null can be used as a key in a HashMap, but it's treated as a special case.

You seem to be using hashCode for a different purpose, so you have to handle is in a specific way.

查看更多
闹够了就滚
4楼-- · 2019-06-24 07:52

Its returning hashCode of an Object not an class.

查看更多
Animai°情兽
5楼-- · 2019-06-24 07:59

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.

查看更多
成全新的幸福
6楼-- · 2019-06-24 08:01

because if it was static "1".hashCode() and "2".hashCode() would have returned the same value, which is obviously wrong.

It is specific per instance, and influenced by it, therefore it cannot be static.

查看更多
登录 后发表回答