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:
xxxxxxxxxx
1
List<MyObject> object = new ArrayList<>();
In this example, we create ArrayList of User
objects
xxxxxxxxxx
1
import java.util.*;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
//create User objects
7
User user1 = new User("Tom", 24);
8
User user2 = new User("Kate", 21);
9
10
// create Array
11
List<User> users = new ArrayList<>();
12
13
// add items to the ArrayLists
14
users.add(user1);
15
users.add(user2);
16
17
System.out.println(users);
18
}
19
}
Output:
xxxxxxxxxx
1
[{name='Tom', age=24}, {name='Kate', age=21}]
User class:
xxxxxxxxxx
1
public class User {
2
private final String name;
3
private final int age;
4
5
public User(String name, int age) {
6
this.name = name;
7
this.age = age;
8
}
9
10
public String getName() {
11
return name;
12
}
13
14
public int getAge() {
15
return age;
16
}
17
18
19
public String toString() {
20
return "{" +
21
"name='" + name + '\'' +
22
", age=" + age +
23
"}";
24
}
25
}
Note:
We are able to print users in the Example class, because we have overridden
toString()
method in the User class.