空字符串的Java String hashCode

编程入门 行业动态 更新时间:2024-10-27 17:18:29
本文介绍了空字符串的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(); }

谢谢.

推荐答案

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

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

本文发布于:2023-11-04 12:35:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557956.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:空字符串   Java   hashCode   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!