EN
Java - create ArrayList of Objects
0
points
In this article, we would like to show you how to create ArrayList of Objects in Java.
Quick solution:
List<MyObject> object = new ArrayList<>();
Practical example
In this example, we create ArrayList of User
objects
import java.util.*;
public class Example {
public static void main(String[] args) {
//create User objects
User user1 = new User("Tom", 24);
User user2 = new User("Kate", 21);
// create Array
List<User> users = new ArrayList<>();
// add items to the ArrayLists
users.add(user1);
users.add(user2);
System.out.println(users);
}
}
Output:
[{name='Tom', age=24}, {name='Kate', age=21}]
User class:
public class User {
private final String name;
private final int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "{" +
"name='" + name + '\'' +
", age=" + age +
"}";
}
}
Note:
We are able to print users in the Example class, because we have overridden
toString()
method in the User class.