2012-08-28 118 views
1

当我们尝试使用toString()打印任何对象时,我们得到了HashCode(如果toString()未被覆盖)。但是,如果我想打印字符串变量的Hashcode,我该怎么做。 这是关于Java的问题。字符串的散列码

+5

'“abc”.hashCode()'? –

+0

“串变量的哈希码”是什么意思?为什么你不能简单地在其上调用'hashCode()'? –

+0

'toString()'不会在默认情况下打印hashCode()。如果这是你想要的,你最好调用'hashCode()'。注意:它可能不是唯一的。 –

回答

8

就叫hashCode()String对象:

String s = "Hello World"; 
System.out.println(s.hashCode()); 

如果你想在相同的格式Object.toString(),试试这个:

System.out.println(Integer.toHexString(s.hashCode())); 
+2

更确切地说:'s.getClass()。getName()+“ @“+ Integer.toHexString(s.hashCode());' – assylias

+0

@assylias Yes ofourse:'”String @“+ Integer.toHexString(s.hashCode()));' – Jesper

+0

@Jesper:ok,hashCode()is对象类的成员。日Thnx。 –

2

您可以通过调用hashCode()方法来获取任何Java对象的哈希码。结果将是一个int,然后您可以打印或做任何你想要的东西。

如果您对Object.toString的实施感兴趣,很容易在grepcode处查询。它说:

public String toString() { 
    return getClass().getName() + "@" + Integer.toHexString(hashCode()); 
} 
2
System.out.println("Some String".hashCode()); 
1

简单请拨打hashcode()方法。它来自Object

String str = "mystring"; 
System.out.println(str.hashCode());