This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Java in General and the fly likes Printing out an array elements has different results?? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Printing out an array elements has different results??" Watch "Printing out an array elements has different results??" New topic
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
    
  19

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Printing out an array elements has different results??
 
Similar Threads
How many objects created for array init
Singleton only creates 1 Instance or more ?
Serialization doubt
How to print reference of String Object ?
Var args once again......