Reputation: 141
So I created three class called "Address", "Job" and "Person" with "Person" being my primary class. I test these by:
Address person2Address = new Address(1054, "Pico St", "Los Angeles", "CA", "97556");
Address person2JobAddress = new Address(5435, "James St", "New York", "NY", "56565");
ArrayList<String> person2Phone = new ArrayList<String>();
person2Phone.add("555-555-55");
Job person2Job = new Job("Mechanic", 35000.00, person2JobAddress);
Person person2 = new Person("Rollan Tico", "New York", 'M', person2Address, person2Job, person2Phone);
System.out.println(person2.toString());
They print everything correctly. Now, this is where I am stuck. How would I create a different class called Persons that stores each Person created in a ArrayList? Would there be any constrcunert? I know that an Arrayist is created by ArrayList<Person> List = new ArrayList<Person>();
, but got a feeling I am missing something.
Upvotes: 0
Views: 802
Reputation: 4360
If you create a class for an object like Person
, you don't need to create a Persons
class just to store multiple Person
objects. Unless you have to define operations which involves multiple Person
Objects, like for example a Group
class with operations performed on group pf persons, in which case creating a Persons
or Group
class makes sense. In your case I would assume you just need to store multiple Person
objects and for that ArrayList<Person>
will suffice.
ArrayList<Person> persons = new ArrayList<Person>();
persons.add(new Person(.....)); //add Person
.
.
Person person1=persons.get(1); //get Person by index
Upvotes: 0
Reputation: 82
You can have Collection like
Collection<Person> persons = new ArrayList<Person>();
persons.add(person2);
Or in some case, like JSON serialization you cannot seralize a list as the root element. so,
import java.util.*
public class Persons {
private Collection<Person> persons;
//If you want the clients to have flexibility to choose the implementation of persons collection.
//Else, hide this constructor and create the persons collection in this class only.
public Persons(Collection<Person> persons) {
this.persons = persons;
}
public void addPerson(Person person) {
persons.add(person);
}
}
Upvotes: 1