Corey
Corey

Reputation: 200

Empty array object creation in Java

I am trying to learn some foundational ways to manipulate certain aspects of coding that stray away from single use and make something more "dynamic" that can kind of build itself on the fly.

For example of what I would like to accomplish, which I believe would consist of using some type of empty array of an object and a loop. I just don't know how to write it.

Lets keep it basic and say I have a Person Class.

public class Person
{
    String name;
    String age;
}

So in my TestDrive I would just get a simple user input to gather information on that person.

Such as...

import javax.swing.JOptionPane;


public class PersonTestDrive
{

    public static void main(String[] args)
    {
        String name;
        String age;


        name = JOptionPane.showInputDialog(null, "Enter your name");
        age = JOptionPane.showInputDialog(null, "Enter your age");

        Person human = new Person();

        human.name = name;
        human.age = age;

        JOptionPane.showInputDialog(null, "Would you like add another entry?");

        /* At this point it would loop if the user wanted to add another entry.
        I would just wrap it all in while loop that just checked if the user said yes or no.
        However, if they do choose to add another entry
        "IF" a human object already existed it would create a
        new human2 object, and then human3, etc. */

    }

}

Upvotes: 0

Views: 309

Answers (1)

Jaroslaw Pawlak
Jaroslaw Pawlak

Reputation: 5578

It sounds that all you need is a collection of objects, such as ArrayList<Person>.

"human" is a name of your variable, and at compile time you don't know how many other variables there can be so you cannot refer to them in the code using "human2", "human3" and so on. You can create these variables, but they may be nulls and your input will also be limited to how many variables you have. Another problem would be keeping track of what variable to assign to next.

With List<Person> list you can do list.get(2) to get third object (it will thrown an exception if there are few than 3) or list.size() to check how many objects were created so far.

Here is some more information about Java collections: http://docs.oracle.com/javase/tutorial/collections/

Upvotes: 1

Related Questions