It is a class that uses a dynamic array for storing the elements.
It can contain duplicate elements.
Maintains insertion order.
Not synchronized.
Random access because array works at the index.
Manipulation slows because a lot of shifting needs to be occurred.
We have Student with age and location. Add multiple students in ArrayList and send it to other layer and other layer should able to iterate over it.
Here, 3 classes are firstly made.
First is JbkStudent having age, location.
Second is JbkStudentArraylist for adding number of Jbkstudents in ArrayList.
Third is JbkStudentTest, having main method from where program is going to start initially.
JbkStudent.java
package com.javabykiran.collection.arraylist;
public class JbkStudent {
public int age;
public String location;
}
JbkStudentArraylist.java
package com.javabykiran.collection.arraylist;
import java.util.ArrayList;
public class JbkStudentArraylist {
ArrayList<JbkStudent> al = new ArrayList<JbkStudent>();
public ArrayList<JbkStudent> showStudentInfo() {
/*----------Adding First Student--------------------*/
JbkStudent s1 = new JbkStudent();
s1.age = 25;
s1.location = "Pune";
al.add(s1);
/*----------Adding Second Student--------------------*/
JbkStudent s2 = new JbkStudent();
s2.age = 26;
s2.location = "Mumbai";
al.add(s2);
/*----------Adding Third Student--------------------*/
JbkStudent s3 = new JbkStudent();
s3.age = 24;
s3.location = "Delhi";
al.add(s3);
/*----------Adding Fourth Student--------------------*/
JbkStudent s4 = new JbkStudent();
s4.age = 27;
s4.location = "Mumbai";
al.add(s4);
/*----------Adding Fifth Student--------------------*/
JbkStudent s5 = new JbkStudent();
s5.age = 25;
s5.location = "Pune";
al.add(s5);
return al;
}
}
JbkStudentTest.java
package com.javabykiran.collection.arraylist;
import java.util.ArrayList;
import java.util.Iterator;
public class JbkStudentTest {
public static void main(String[] args) {
JbkStudentArraylist sal = new JbkStudentArraylist();
ArrayList<JbkStudent> arraylist = sal.showStudentInfo();
Iterator itr = arraylist.iterator();
while (itr.hasNext()) {
Object obj = itr.next();
JbkStudent stu = (JbkStudent) obj;
System.out.println("Student Age is : " + stu.age);
System.out.println("Student Location is : " + stu.location);
System.out.println("****************************");
}
}
}