0

我必须重写 toString() 方法,我已经这样做了,如下所示

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;
}

并创建了另一种方法来打印它

public void print() {
    System.out.println(park.toString());
}

不知何故,当我在我的 main 方法中使用 print 方法时,出现以下情况

[LAnimal;@3a67ad79

现在,有人向我建议,我实际上可能正在使用默认的 toString() 方法,因此带来了实际的地址内存。

大家觉得问题出在哪里?

4

4 回答 4

2

从使用park.length和应用程序输出看来,它park是一个类型为 的数组Animal所以

System.out.println(park.toString());

应该

System.out.println(Arrays.toString(park));

(因为Arrays不要覆盖该Object#toString方法)

于 2013-11-07T12:34:03.917 回答
2

您不能覆盖toString数组,Arrays#toString而是使用。

于 2013-11-07T12:33:36.487 回答
0

park[i]你在你的toString()方法中打印

str += '\n' + "cage " + i + " status: " + park[i];

                                          ^
                                          |_________ Here you are printing the Object
于 2013-11-07T12:33:59.633 回答
0

你必须添加@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;
}
于 2013-11-07T12:27:37.430 回答