gpt4 book ai didi

java - 不能在 ArrayList 中使用对象的 toString() 方法

转载 作者:搜寻专家 更新时间:2023-11-01 02:12:23 24 4
gpt4 key购买 nike

我正在尝试使用 ArrayList 中对象的 toString() 方法,它打印的是内存地址而不是预期值。我把我的类(class)翻译成英文,如果我忘记了什么,抱歉,如果你不明白,就去问吧。 让我们看看我的代码:

调度类(我抑制了 getter 和 setter):

static Professor professor;
static Room room;
static Classroom classroom;

public String toString() {
return "Schedule [getProfessor()=" + getProfessor() + ", getRoom()="
+ getRoom() + ", getClassRoom()=" + getClassRoom() + ", getClass()=" + getClass() + ", hashCode()="
+ hashCode() + ", toString()=" + super.toString() + "]";
}

学校

ArrayList<Professor> professor = new ArrayList<Professor>();
ArrayList<Room> room = new ArrayList<Room>();
ArrayList<Classroom> classroom = new ArrayList<Classroom>();
public ArrayList<Schedule[][]> sched = new ArrayList<Schedule[][]>();

我正在使用遗传算法(目前我正在学习它,所以,我知道的不多),这是我的“人口生成器”:

人口

public static void generatePopulation(School school){

// Shuffle the arraylist for generate a random population
Collections.shuffle(school.getProfessor());
Collections.shuffle(school.getClassroom());
Collections.shuffle(school.getRoom());

Schedule[][] sched1 = new Schedule[1][1];

// Generate population (just a little test to see if it works)
sched1[0][0].addEverything(school.getProfessor().get(0), school.getClassroom().get(0), school.getRoom().get(0));
school.sched.add(sched);

主要

 (... school and associations created ...)
Population.generatePopulation(school);
System.out.println(school.getSched().isEmpty()); // it returns false, that is, isn't empty
System.out.println(school.getSched().get(0).toString());
// returns "[[Lentidades.Schedule;@40914272" (entidades = name of my package)

那么,为什么我收到的是内存位置而不是预期值?我想我什么都没有忘记,但是如果您在此代码中看到一些奇怪的地方,请发送一个问题,我会解释/粘贴剩余的代码。

最佳答案

您正在接收 Schedulearray,因此永远不会使用您的 toString() 方法。

查看 [[Lentidades.Schedule;@40914272 输出的 [[ 部分,这告诉您二维 数组 正在打印。

正如@JonSkeet 和@MarounMaroun 指出的那样,打印数组 的一种简单方法是使用Arrays.toString()。对于一维数组,或Arrays.deepToString()对于多维。

关于java - 不能在 ArrayList 中使用对象的 toString() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16134998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com