André Fecteau
André Fecteau

Reputation: 140

Saving object for later use

I am trying to practice and get better at creating objects and using them effectively. To practice I have made a class called Person and inside of this class I define that each person has a first name, last name, and age. I have methods to allow other classes to set the first name, last name, and age of person and then also return those values. This is where I am stuck. I would like to be able to do all of that, take in first and last name with age, but save that somewhere so that later I could use it. Example is making a student list for a school course. I would like to be able to take in and store that Person class a specific an object in an array or something along those lines. I did try to do this using an ArrayList but it doesn't output right for some reason. Any help? thanks!

    import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {

        Person definePerson;
        String name;
        int age;
        ArrayList<Person> persons = new ArrayList<Person>();

        definePerson = new Person();
        System.out.print("Please Enter the first name: ");
        name = definePerson.enterFirst();
        System.out.print("Please Enter the last name: ");
        name = definePerson.enterLast();
        System.out.print("Please Enter their age: ");
        age = definePerson.enterAge();
        persons.add(definePerson);
        System.out.println("The Person ArrayList is: " + persons.toString());

    }
}

Upvotes: 1

Views: 199

Answers (3)

Anubian Noob
Anubian Noob

Reputation: 13596

The problem is that Java doesn't know how to convert a Person object to a displayable string. You have to write a toString method to do so.

Here's an example:

@Override
public String toString() {
    return name + ": " + age + " years old.";
}

This methods needs to be in your person class so that the ArrayList object knows how to display your object.

Here's the toString method documentation from AbstractCollection.java:

Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).

Upvotes: 3

Shawn Jacobson
Shawn Jacobson

Reputation: 1352

ArrayList.toString will not output the items in the list, you need to iterate the ArrayList and print out the elements contained within.

Upvotes: 0

techPackets
techPackets

Reputation: 4504

You have to override the toString() method in your Person class.

Person class

class Person{
 String name;
 int age;

 public String toString(){    
  return "person's name"+name+"person's age"+age;    
}

Upvotes: 3

Related Questions