Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to store the objects of a class in an ArrayList.

Java Code Example — Collection Programs

ADVERTISEMENT

Java Program to store the objects of a class in an ArrayList.

Objective

Write a Java program to store custom objects (Student) in an ArrayList.

Algorithm / Approach

  1. Create a Student class with input() and display() methods.
  2. In main, create an ArrayList<Student>.
  3. Use a loop to add 5 new Student objects to the list.
  4. Pass the list to a handler method.
  5. Iterate through the list, extract each student using al.get(i), cast it to Student, and call their methods.
Student.java
import java.util.*;
class Student {
 int roll;
 String name;
 Scanner s=new Scanner(System.in);
 public void input() {
  System.out.print("Enter Roll: ");
  roll=Integer.parseInt(s.nextLine());
  System.out.print("Enter Name: ");
  name = s.nextLine();
 }
 public void display() {
  System.out.println("Name- "+name);
  System.out.println("Roll- "+roll);
 }
}
class ListUse {
 public void listUse(ArrayList al) {
  for(int i =0; i< al.size(); i++) {
   Student s=(Student) al.get(i);
   s.input();
  }
  for(int i =0; i< al.size(); i++) {
   Student s = (Student) al.get(i);
   s.display();
  }
 }
} 
class Test {
 public static void main(String[] s)
 {
  ArrayList<Student> al = new ArrayList();
  al.add(new Student());
  al.add(new Student());
  al.add(new Student());
  al.add(new Student());
  al.add(new Student());
  ListUse lu=new ListUse();
  lu.listUse(al); 
 }
}

Expected Output

Enter Roll: 12
Enter Name: Alok
Enter Roll: 13
Enter Name: Suraj
Enter Roll: 14
Enter Name: Gunja
Enter Roll: 15
Enter Name: Richa
Enter Roll: 16
Enter Name: Aditya
Name- Alok
Roll- 12
Name- Suraj
Roll- 13
Name- Gunja
Roll- 14
Name- Richa
Roll- 15
Name- Aditya
Roll- 16

Explanation of the Program

  • Collections can hold any type of Object, including custom classes you create yourself.
  • Notice the casting: Student s = (Student) al.get(i);. If the ArrayList was declared broadly as ArrayList al = new ArrayList(); without a generic type parameter, the get() method returns a generic Object. You must explicitly cast it back to a Student before you can access the input() or display() methods.

Complexity

Time Complexity O(n) - To iterate through the list.
Space Complexity O(n) - Memory for the n Student objects.
ADVERTISEMENT