Arraylist of objects in Java with simple code example: Learn how to store user defined objects into an ArrayList.
Here is the declaration of the ArrayList will be used to store objects of the Book class.
ArrayList<Book> list = new ArrayList<Book>();
In the angle bracket, notice the class name Book. It’s similar to the array list declaration for other data types e.g. for String data types, below syntax we use
ArrayList<String> list = new ArrayList<String>();
FYI, Before you move to code example, My book for you.
ArrayList of Objects Code Example in Java:
In this code example, we’ll create multiple objects of the books class and add to the ArrayList.
And then, we’ll print the book’s name and id by fetching objects from the ArrayList.
import java.util.ArrayList;
class Book {
String name;
int id;
public Book(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
}
public class ArrayListOfObjectsTest {
public static void main(String[] args) {
ArrayList<Book> list = new ArrayList<Book>();
list.add(new Book("OOP Concepts Booster", 1));
list.add(new Book("IT Jobs Made Easy for Freshers", 2));
list.add(new Book("Head First Design Patterns", 3));
//Print book's name and id from the ArrayList.
for (Book b : list) {
System.out.println(b.getName() + " " + b.getId());
}
}
}
OUTPUT:
OOP Concepts Booster 1
IT Jobs Made Easy for Freshers 2
Head First Design Patterns 3
Next, You can learn sharing of ArrayList between different classes in java