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
- Create a
Studentclass withinput()anddisplay()methods. - In main, create an
ArrayList<Student>. - Use a loop to add 5 new
Studentobjects to the list. - Pass the list to a handler method.
- Iterate through the list, extract each student using
al.get(i), cast it toStudent, 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 asArrayList al = new ArrayList();without a generic type parameter, theget()method returns a genericObject. You must explicitly cast it back to aStudentbefore you can access theinput()ordisplay()methods.
Complexity
Time Complexity
O(n) - To iterate through the list.
Space Complexity
O(n) - Memory for the n Student objects.