Store User-Defined Objects in Collections

The power of collections is that they can store any type of object, including objects of classes that you create. For example, consider the following example that uses a LinkedList to store Store User-Defined Objects.

Program

0

Program Source

import java.util.LinkedList;

class StudentData {
    
    String name;
    int age;
    
    StudentData(String na, int ag)
    {
        name = na;
        age = ag;
    }
    
    String getData()
    {
            return "Name : "+name+"  Age : "+age;
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        LinkedList list1 = new LinkedList();
        list1.add(new StudentData("Haj",20));
        list1.add(new StudentData("Raj",19));
        list1.add(new StudentData("Sar",18));
        list1.add(new StudentData("Kan",17));
        
        for(StudentData x : list1)
        {
            System.out.println(x.getData());
        }
    }
}

Leave a Comment