Strings are objects, objects can be added to a list. Let’s examine this in more detail. Assume we have access to the class that’s define below:

public class Person {

    private String name;
    private int age;
    private int weight;
    private int height;

    public Person(String name) {
        this.name = name;
        this.age = 0;
        this.weight = 0;
        this.height = 0;
    }

    public String getName() {
        return this.name;
    }

    public int getAge() {
        return this.age;
    }

    public void growOlder() {
        this.age = this.age + 1;
    }

    public void setHeight(int newHeight) {
        this.height = newHeight;
    }

    public void setWeight(int newWeight) {
        this.weight = newWeight;
    }

    public double bodyMassIndex() {
        double heightDivByHundred = this.height / 100.0;
        return this.weight / (heightDivByHundred * heightDivByHundred);
    }

    @Override
    public String toString() {
        return this.name + ", age " + this.age + " years";
    }
}

In the example below we first create a list meant for storing Person type object, after which we add persons to it. Finally the person objects are printed one by one.

ArrayList<Person> persons = new ArrayList<>();

// a person object can be created first
Person john = new Person("John");
// and then added to the list
persons.add(john);

// person objects can also be created "in the same sentence" that they are added to the list
persons.add(new Person("Jack"));
persons.add(new Person("Andrew"));

for (Person person: persons) {
    System.out.println(person);
}

Adding user-inputted objects to a list

Below is an example of adding users to a list:

Scanner scanner = new Scanner(System.in);
ArrayList<Person> persons = new ArrayList<>();

// Read the names of persons from the user
while (true) {
    System.out.print("Enter a name, empty will stop: ");
    String name = scanner.nextLine();
    if (name.isEmpty()) {
        break;
    }

  persons.add(new Person(name));

Add to the list a new person whose name is the previous user input.

persons.add(new Person(name));

Print the number of the entered persons, and their individual information:

System.out.println();
System.out.println("Persons in total: " + persons.size());
System.out.println("Persons: ");

for (Person person: persons) {
    System.out.println(person);
}

My site is free of ads and trackers. Was this post helpful to you? Why not BuyMeACoffee