-Uses dynamic array for storing - algorithm
-Can contain duplicate
-not syncronized (It is not Thread safe, So It is lower performance)
-Maintain order
-Random access
-Manipulation slow because a lot of shifting needs to be occurred.
ArrayList has mainly two methods
-add() - Add the elements on ArrayList
-get() - get the elements from the ArrayList
Example of Basic ArrayList (print the data with iterator) code..
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListBasic {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add("Najathi");
al.add("Naharni");
al.add("Nazaaha");
al.add("Thahlan");
al.add("Thahani");
Iterator i = al.iterator();
while (i.hasNext()){
System.out.println(i.next());
}
}
}
Example of Basic ArrayList (print the data with iterator) code..
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListBasicFor {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add("Najathi");
al.add("Naharni");
al.add("Nazaaha");
al.add("Thahlan");
al.add("Thahani");
for(Object obj:al){
System.out.println(obj);
}
}
}
addAll - add the elements to a1 object.
remove all - it will remove a2 object same elements of a1 object also.
retain all - it will compair to object and display only common object.
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListAddAll {
public static void main(String[] args) {
ArrayList a1 = new ArrayList();
ArrayList a2 = new ArrayList();
//add the elements to a1 object
a1.add("Najathi");
a1.add("Naharni");
a1.add("Nazaaha");
//add the elements to a2 object
a2.add("Thahlan");
a2.add("Thahani");
a2.add("Najathi");
//addAll - add the elements to a1 object
//a1.addAll(a2);
//remove all - it will remove a2 object same elements of a1 object also.
//a1.removeAll(a2);
//retain all - it will compair to object and display only common object
a1.retainAll(a2);
Iterator i = a1.iterator();
while(i.hasNext()){
System.out.println(i.next());
}
}
}
Student's Data Array List code ( User defined object in ArrayList )..
import org.omg.PortableInterceptor.ServerRequestInfo;
import java.util.ArrayList;
import java.util.Iterator;
//User defined object in ArrayList
public class StudentArrayList {
int rollNo;
String name;
int age;
public StudentArrayList(int rollNo,String name,int age){
this.rollNo=rollNo;
this.name=name;
this.age=age;
}
}
class Simple {
public static void main(String[] args) {
StudentArrayList s1 = new StudentArrayList(101, "Najathi", 22);
StudentArrayList s2 = new StudentArrayList(101, "Naharni", 21);
StudentArrayList s3 = new StudentArrayList(101, "Nazaaha", 15);
ArrayList al = new ArrayList();
al.add(s1);
al.add(s2);
al.add(s3);
Iterator i = al.iterator();
while (i.hasNext()){
StudentArrayList st = (StudentArrayList) i.next();
System.out.println(st.name + " " + st.name+ " "+st.age);
}
}
}
No comments:
Post a Comment