0

So I have a class called Persons that the moment has a method to add Person objects when created in main.

import java.util.*;

public class Persons {

public ArrayList<Person> personsList = new ArrayList<Person>();

   public boolean addPerson(Person newPerson) {
       personsList.add(newPerson);
       return true;
   }
}

This is my main method

import java.util.*;

public class testPersons {

public static void main(String[] args) {

Persons persons = new Persons();

    Address person1Address = new Address(xxx, "xxx", "xxx", "CA", "xxx");
    Address person1JobAddress = new Address(1542, "High St", "Santa Cruz", "CA", "94063");
    ArrayList<String> person1Phone = new ArrayList<String>();
    person1Phone.add("xxx-xxx-xxx");
    Job person1Job = new Job("Teacher", 25000.00, person1JobAddress);
    Person person1 = new Person("xxxxxxx", "San Mateo", 'M', person1Address, person1Job, person1Phone);

    persons.addPerson(person1);

    System.out.println(persons);
   }
}

So my question is, "How would I add the object Persons1 into my arrayList in Persons class?" It does compile, but I when run it, I get weird gibberish. Would it be I'm missing something in my Persons class, main or can I not print the objects in ArrayList like I did?

HPotter
  • 141
  • 2
  • 11
  • Printing an object, by default, will just print the `hashCode()` of the object. If you want it to loop through the object and print all the objects it contains, you need to write code to do that. – D M Jan 27 '17 at 22:40
  • You printing the "default" results of `Persons`. The general suggestion will be to override `toString`, personally I find this a bad idea, `toString` should be reserved for debugging. In your case, you could just iterate over the `personsList` instead – MadProgrammer Jan 27 '17 at 22:40
  • why on earth should `toString()` be reserved for debugging? – D M Jan 27 '17 at 22:41

1 Answers1

0

Make sure all your Person related classes including Person override the default toString().

when you System.out.println(persons), this happens:

  • The Person objects in your ArrayList are called one by one.
  • For each Person object, its toString() is method is called. If toString() is not overridden, the Object (default) toString will be called. Hence the "weird gibberish". You need to tell java what kind of "presentation" you would like to show by overriding the toString()
Minjun Yu
  • 3,497
  • 4
  • 24
  • 39