简体   繁体   中英

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

    }
}

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

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

ArrayList.toString将不会输出列表中的项目,您需要迭代ArrayList并打印出其中包含的元素。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM