Header Ads

Header ADS

User-defined class objects in Java ArrayList

User-defined class objects in Java ArrayList

Let's see an example where we are storing Student class object in an array list.
  1. class Student{  
  2.   int rollno;  
  3.   String name;  
  4.   int age;  
  5.   Student(int rollno,String name,int age){  
  6.    this.rollno=rollno;  
  7.    this.name=name;  
  8.    this.age=age;  
  9.   }  
  10. }  
  1. import java.util.*;  
  2.  class ArrayList5{  
  3.  public static void main(String args[]){  
  4.   //Creating user-defined class objects  
  5.   Student s1=new Student(101,"Sonoo",23);  
  6.   Student s2=new Student(102,"Ravi",21);  
  7.   Student s2=new Student(103,"Hanumat",25);  
  8.   //creating arraylist  
  9.   ArrayList<Student> al=new ArrayList<Student>();  
  10.   al.add(s1);//adding Student class object  
  11.   al.add(s2);  
  12.   al.add(s3);  
  13.   //Getting Iterator  
  14.   Iterator itr=al.iterator();  
  15.   //traversing elements of ArrayList object  
  16.   while(itr.hasNext()){  
  17.     Student st=(Student)itr.next();  
  18.     System.out.println(st.rollno+" "+st.name+" "+st.age);  
  19.   }  
  20.  }  
  21. }  
       101 Sonoo 23
       102 Ravi 21 
       103 Hanumat 25 

No comments

Theme images by Matt Vince. Powered by Blogger.