Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array of object reference elements display

 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic