Cannot use the toString () method of an object inside an ArrayList

I am trying to use the toString() method of an object inside an ArrayList , and instead it prints the memory address, not the expected values. I translated my classes into English, sorry if I forget something, just a quest if you do not understand. Check out my code:

Schedule class (I suppressed getters and setters):

 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() + "]"; } 

School

 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[][]>(); 

I use the genetic algorithm (the moment I find out about this, therefore, I don’t know much), here is my “population generator”:

Population

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

home

  (... 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) 

So why am I getting a memory position instead of the expected values? I think I forgot nothing, but if you see something strange in this code, just submit a question and I will explain / paste the remaining code.

+4
source share
1 answer

You get an array from Schedule s, so your toString() method is never used.

Look at the [[ output [[Lentidades.Schedule;@40914272 , this suggests that a 2-dimensional array is being printed.

As @JonSkeet and @MarounMaroun points out, a simple way to print arrays is to use Arrays.toString() for one-dimensional arrays or Arrays.deepToString() for multi-dimensional.

+6
source

All Articles