Multiple instance of class versus array Java
Solution 1:
I would prefer the first way because there is a rare need to create a wrapper class for keeping a collection (like Persons
-> Person
). It makes sense if the class Persons
gets renamed to a Company
/Community
, which contains a List
of workers/persons and provides specific operations over this list.
public String showAllMembers() { ... }
public void notifyAllMembers() { ... }
Also, the second way breaks the Single responsibility principle. It shouldn't take care about printing a person, the class is responsible for adding/removing them. The Persons
can provide to you a specific Person
, then you have to call a method print()
on a given instance:
Persons persons = ...;
persons.getMember(10).print();
Lets say i have 10 000 of these persons. Is there any downside to create 10 000 instance of class?
In any case, you will have to create 10000+ instances. Consider,
-
10000
Person
s + aList
-
10000
Person
s + aPersons
+ aList
Solution 2:
The first one is more object-oriented than the second, which becomes apparent as soon as you start adding more properties to a person.
For example, consider adding a date of birth to a person. When you have class Person
, you modify the class, and everyone who has access to it will be able to get it. You will also be passing the date of birth with the Person
object, so any method that takes Person
as a parameter will have access to that person's date of birth:
static void displayPerson(Person p) {
// Here, we can print both the name and the date of birth / age
}
public static void main(String[] args) {
...
displayPerson(people.get(0));
}
The second approach would require adding a parallel collection to the Persons
class. All users of Persons
would get access to date of birth, but unless a method takes the full collection as a parameter, it would have access to only the properties that the caller takes from the collection:
void displayPerson(String name) {
// Here, we have no access to person's date of birth
}
public static void main(String[] args) {
...
displayPerson(persons.print(0));
}