aspose file tools*
The moose likes Beginning Java and the fly likes Array of object reference elements display Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array of object reference elements display" Watch "Array of object reference elements display" New topic
Author

Array of object reference elements display

Shiva Mohan
Ranch Hand

Joined: Jan 05, 2006
Posts: 477
Hi,

When I do array of primitive elements initialization like

int[] key={4,5,6};

and in the static main method, I created
System.out.println(notes.key[0]);-----------it gave output 4

But ,in object references array elements initialization

Dog[] myDogs={puppy,new Dog("Clover"),new Dog("Aiko")};

In a static main method, I created
System.out.println(notes.myDogs[0]);//--------------it just gave some address.

1.Why is it giving address?
2.To get the result puppy,what should I include and where?

Please,Help me.
Manuel Palacio
Ranch Hand

Joined: Oct 16, 2000
Posts: 45
You have to override the toString() method in Dog and print the dog name there.

Otherwise it returns (default impl)
[ April 25, 2006: Message edited by: Manuel Palacio ]

<a href="http://www.newinstance.net" target="_blank" rel="nofollow">http://www.newinstance.net</a>
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Manuel is exactl right; I just wanted to point out that this actually has nothing to do with arrays, and you'd see exactly the same result with

System.out.println(puppy);


[Jess in Action][AskingGoodQuestions]
Shiva Mohan
Ranch Hand

Joined: Jan 05, 2006
Posts: 477
Hi Manuel and Ernest,

Thanks for the reply.This is the first time i am using hashcode and toSting().I used the below line

System.out.println( mypuppy.myDogs[0]+"@"+Integer.toHexString(mypuppy.hashCode()));

It is still giving the same(address).Why? Please,Help me in the above line anything is wrong.
Shiva Mohan
Ranch Hand

Joined: Jan 05, 2006
Posts: 477
Hi,

Thanks.I figured that out by myself.Do i need to override toString() for every array element.

for example,displaying myDogs[1]="Clover" data ,do i need to overide one more toString() method that returns Clover.
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
Originally posted by Shiva Mohan:
Hi,

Thanks.I figured that out by myself.Do i need to override toString() for every array element.

for example,displaying myDogs[1]="Clover" data ,do i need to overide one more toString() method that returns Clover.


You need to override toString() in the class Dog, which is exactly what the first reply said. Ex:

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Array of object reference elements display