java 空字符串的Java String hashCode

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6981968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:08:22  来源:igfitidea点击:

Java String hashCode of null string

javastringstaticnull

提问by user710818

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:

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

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

Thanks.

谢谢。

回答by Joachim Sauer

As others have noted hashCodeis a method on Objectand is non-static because it inherently relies (i.e. belongs to) an object/instance.

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

Note that Java 7 introduced the Objectsclass, which has the hashCode(Object)method, which does exactly what you want: return o.hashCode()if ois non-null or 0otherwise.

请注意,Java 7 引入了Objects具有hashCode(Object)方法的类,该方法完全符合您的要求:o.hashCode()如果o为非空0则返回。

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

此类还有其他处理可能null值的方法,例如equals(Object, Object)toString(Object)以及其他一些方法。

回答by amit

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

因为如果它是静态的"1".hashCode()并且"2".hashCode()会返回相同的值,这显然是错误的。

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

每个实例都是特定的,并受其影响,因此它不能是静态的。

回答by Jens Schauder

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.

使用相同的思路,您可以使每个方法都是静态的。

回答by JB Nizet

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

hashCode用于获取一个对象的hashCode,以便知道HashMap这个对象必须放在哪个bucket中。因此它必须是对象的实例方法,并且必须以多态方式调用。

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

null可以用作 HashMap 中的键,但它被视为一种特殊情况。

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

您似乎将 hashCode 用于不同的目的,因此您必须以特定方式处理。

回答by Jigar Joshi

Its returning hashCode of an Objectnot an class.

它返回的Object不是类的hashCode 。