Hashcode de una cadena

When we try to print any object using toString() we get the HashCode (if toString() is not overriden). But, If I want to print the Hashcode of the String Variable, what should I do. This question it is with respect to Java.

preguntado el 28 de agosto de 12 a las 14:08

What do you mean by "hash code of the String variable"? Why can't you simply call hashCode() ¿en eso? -

toString() doesn't just print the hashCode() by default. You are better off calling hashCode() if that is what you want. Note: it might not be unique. -

you don't get the hashcode, you get the objectId. -

@JoeriHendrickx And what would objectid be, this is not a standard Java term? -

@PetarMinchev There is no hay tal cosa as a unique hashCode implementation, except for objects whose total number of possible states fits into an int. Such objects are muy raro. -

4 Respuestas

Solo llama hashCode() en el String :

String s = "Hello World";

If you want it in the same format as Object.toString(), prueba esto:


Respondido 28 ago 12, 14:08

Más precisamente: s.getClass().getName() + "@" + Integer.toHexString(s.hashCode()); - Assylias

@assylias Yes ofcourse: "String@" + Integer.toHexString(s.hashCode())); - Jesper

@Jesper: ok, hashCode() is the member of the object class. Thnx. - Biswanath Chowdhury

System.out.println("Some String".hashCode());

Respondido 28 ago 12, 14:08

You can get the hash code of any Java object by invoking the hashCode() method. The result will be an int that you can then print or do anything else you want with it.

If you are interested in the implementation of Object.toString, it is very easy to check at códigogrep. Dice:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());

Respondido 28 ago 12, 15:08

Simplemente llame al hashcode() method. It comes from Object.

String str = "mystring";

Respondido 28 ago 12, 14:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.