简体   繁体   中英

Java - How can I create an array of a different class and iterate through it calling its toString method?

I have a Person class with the fields "name" and "phoneNumber" that are set through the constructor. I am trying to create a separate testing class that will create an array of Person and iterate through them by calling to their toString() method. I am not sure how to do this, any help is appreciated.

Here is my first class which is all I have so far;

public class Person
{
    private String name;
    private String phoneNumber;

    public Person(String name, String phoneNumber)
    {
        this.name = name;
        this.phoneNumber = phoneNumber;
    }
    public String getName()
    {
        return name;
    }
    public String getNumber()
    {
        return phoneNumber;
    }
    public String getPerson()
    {
        return name + " " + phoneNumber;
    }
    @Override
    public String toString()
    {
        return "["+getPerson()+"]";
    }
}

Hope this will help,

public class Test {

    public static void main(String[] args) {

        Person array[] = {new Person("Jason", "123456"), new Person("Karl", "78945"), new Person("Tom", "789456")};

        for(int i = 0; i < array.length; i++){
            array[i].toString();
            //System.out.println(array[i].toString());
        }
    }

}

class Person
{
    private String name;
    private String phoneNumber;

    public Person(String name, String phoneNumber)
    {
        this.name = name;
        this.phoneNumber = phoneNumber;
    }
    public String getName()
    {
        return name;
    }
    public String getNumber()
    {
        return phoneNumber;
    }
    public String getPerson()
    {
        return name + " " + phoneNumber;
    }
    @Override
    public String toString()
    {
        return "["+getPerson()+"]";
    }
}

Save the file as Test.java

Firstly the toString method is for an INDIVIDUAL Person object, and cannot be applied to a whole set, you need to make the method static and have a whole static array defined in the class to be able to go through all instances of the Person class.

private static Person[] pArray = new Person[20]; 
//I picked 20 randomly, if you want any possible number use an arrayList<Person> 

private static int count = 0;

In the constructor

pArray[count] = this;
count++;

Then your toString method:

String list = "[";
for(Person p : this.pArray)
   list = list + p.getPerson() + " ,"
list = list + "]";
return list;

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