空字符串的Java String hashCode [英] Java String hashCode of null string

查看:68
本文介绍了空字符串的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.

这篇关于空字符串的Java String hashCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆