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
Java String hashCode of null string
提问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 hashCode
is a method on Object
and is non-static because it inherently relies (i.e. belongs to) an object/instance.
正如其他人所指出的,hashCode
是一种方法Object
并且是非静态的,因为它本质上依赖(即属于)一个对象/实例。
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.
请注意,Java 7 引入了Objects
具有hashCode(Object)
方法的类,该方法完全符合您的要求:o.hashCode()
如果o
为非空0
则返回。
This class also has other methods that deal with possibly-null
values, 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
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.
hashCode
用于获取一个对象的hashCode,以便知道HashMap
这个对象必须放在哪个bucket中。因此它必须是对象的实例方法,并且必须以多态方式调用。
null
can 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 Object
not an class.
它返回的Object
不是类的hashCode 。