| Author |
Printing out an array elements has different results??
|
Sky Loi
Ranch Hand
Joined: Oct 06, 2008
Posts: 65
|
|
I try the following codes
My concern is why objArray1[1] is printed out with different result (hashcode) ??
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16687
|
|
My concern is why objArray1[1] is printed out with different result (hashcode) ??
How is it a concern? The same object's hashcode isn't changing is it? By default, the Object class uses the identity hashcode as it's hashcode, which is based on some internal formula (which I think uses the memory address at instantiation, but that's not relevant).
In your case, different runs instantiate different objects, and hence, different objects in the array, with different hashcodes.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Sky Loi
Ranch Hand
Joined: Oct 06, 2008
Posts: 65
|
|
Thanks for reply, Henry.
I did more tests as below:
Output is:
java.lang.Object@9304b1
java.lang.Object@190d11
Seems I change the print order. The result is the same with Code 1. Comparing with Code 1, as the arrays are created in the approach, and the print out should be different order with Code 1 (as print out represent their hashcode or address). Please correct me if I am in the wrong idea.
Thank you very much.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
You can't compare the hashCode of instances of Object (and that is what's printed after the @) between JVM invocations, because there is no guarantee whatsoever that they will be the same. You can only guarantee this if your class has overridden hashCode().
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Sky Loi
Ranch Hand
Joined: Oct 06, 2008
Posts: 65
|
|
|
Thanks, Rob.
|
 |
 |
|
|
subject: Printing out an array elements has different results??
|
|
|