Reputation: 532
I have to override the toString() method and I have done so as below
public String toString() {
String str = "The zoo is capable of keeping " + park.length + "animals\nThe following is the list of animals currently in the zoo.";
for(int i = 0; i < park.length; i++)
str += '\n' + "cage " + i + " status: " + park[i];
return str;
}
and created another method to print this
public void print() {
System.out.println(park.toString());
}
Somehow when I use the print method in my main method, the following comes up
[LAnimal;@3a67ad79
Now, someone suggested to me that I might actually be using the default toString() method and hence bringing the actual address memory.
What do you guys reckon the problem is?
Upvotes: 0
Views: 234
Reputation: 159874
From the use of park.length
and the application output it appears that park
is an array of type Animal
. Therefore
System.out.println(park.toString());
should be
System.out.println(Arrays.toString(park));
(since Arrays
don't override the Object#toString
method)
Upvotes: 2
Reputation: 26084
You are printing park[i]
within you toString()
method
str += '\n' + "cage " + i + " status: " + park[i];
^
|_________ Here you are printing the Object
Upvotes: 0
Reputation: 96016
You cannot override toString
for array, use Arrays#toString
instead.
Upvotes: 2
Reputation: 148
you must add @Override
@Override public String toString() {
String str = "The zoo is capable of keeping " + park.length + "animals\nThe following is the list of animals currently in the zoo.";
for(int i = 0; i < park.length; i++)
str += '\n' + "cage " + i + " status: " + park[i];
return str;
}
Upvotes: 0