空字符串的Java String hashCode

空字符串的Java String hashCode

问题描述:

有趣的是,为什么java.lang.String 中的hashCode() 方法不是静态的?在 null 返回的情况下,例如-1 ?因为经常需要做一些事情:

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();
}

谢谢.

正如其他人所指出的 hashCodeObject 上的一个方法并且是非静态的,因为它固有地依赖(即属于)一个对象/实例.

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.

请注意,Java 7 引入了Objects 类,其中包含 hashCode(Object) 方法,这正是你想要的: return o.hashCode() if o 为非 null 或 0 否则.

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.

该类还有其他处理可能-null 值的方法,例如 equals(Object, Object), toString(对象) 和其他一些.

This class also has other methods that deal with possibly-null values, such as equals(Object, Object), toString(Object) and a few others.