TiraULTI TiraULTI - 1 year ago 66
Java Question

What name to give to objects when adding to ArrayList

I have a container class with an array list defined for a Person object.

The person who is using the program is asked to register a person and I have to create the object Person, give it the name, lastname and age the user inputed and after that add it to the ArrayList.

My question is, when creating the Person object, can I give the same name to every object I add? Or do I have to name them person1, person2, etc?

If so, how?


Answer Source

No, you don't have to give them different names. Doing so would actually defeat the purpose of using a collection. You can just do the following:

Person p = new Person(...);
// set name, age, etc.

Each time you do that, a new Person is created and added to the list. Think of the name p as just a temporary variable that can be discarded.