Question with java.lang.Object.hashCode()

Question:
1.In the Java API Doc, i saw the statement below:

This integer need not remain consistent from one execution of an application to another execution of the same application.

Does it mean that on each execution, the hashcode may be different?
But I run this programme(fragment below) sereral times:
System.out.println("c1 hashcode: " + c1.hashCode());
System.out.println("c2 hashcode: " + c2.hashCode());


They return the same code, why?


2.I saw this statement:
It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

Does it mean that it's possible that unequal objects should produce the same hash code? If it does, how to avoid it?

____________________________________________________________________________

Answers:
> They return the same code, why?

The docs say that it need not be consistent. But it doesn't say that it will not be consistent at all. It might give you the same value.

> Does it mean that it's possible that unequal objects
> should produce the same hash code? If it does, how to
> avoid it?

If you override the hashCode() method in the Object to provide a new implementation in your class, this might be possible. HashMap uses the hashCode to lookup for objects, hence it is advised to have them unique. The uniqueness is not an essential characteristic of the hashCode() method.



It means that if you run your program several times, the "same" object may have a different hashcode each time.

Within one run of your application, if you call hashcode multiple times on the same object (and you haven't changed the state of that object) you must get the same value each time.


the hashcode is calculating according object's content. If the two different object has the same content, the hashcode maybe the same. For example,
String a = new String("james");
String b = new String("james");
System.out.println(a.hashCode());
System.out.println(b.hashCode());
The result will show two same integers.

In another case. the hashCode() is according algorithm. For example. I can create my class and override the hashCode() method like:

class A {
int a;
int hashCode() {
return a % 10;
}
}

Thsu, when a is 7, 17, 27 and so on, their hashcode will be same one.


In cases where the programmer has implemented the hashCode method. It is highly unlikely that the design would change the hashCode on subsequence runs of the jvm. If hashCode has not been implemented, it will almost certainly change.
原文地址:https://www.cnblogs.com/johnny/p/123300.html