• Post Reply Bookmark Topic Watch Topic
  • New Topic

Printing out an array elements has different results??  RSS feed

 
Sky Loi
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I try the following codes


My concern is why objArray1[1] is printed out with different result (hashcode) ??
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Sky Loi
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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().
 
Sky Loi
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Rob.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!