Exapmple code for using java.utill.ArrayList
package example.util;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Vector;
public class ArrayListExample {
public void arrayListExample(){
//Create ArrayList Object
ArrayList arrayList=new ArrayList();
//Store data to ArrayList
arrayList.add("value1");
arrayList.add("value2");
arrayList.add("value3");
arrayList.add("value4");
arrayList.add("value5");
//Test Print all data with toString()
System.out.println("ArrayList Data befor "+arrayList);
//Remove data from ArrayList
String removeValue=arrayList.remove(2);
boolean remove1=arrayList.remove("value1");
boolean remove2=arrayList.remove("value3");
Vector v=new Vector();
v.add("value2");
boolean remove3=arrayList.removeAll(v);
//Removed data can return in VAL
System.out.println("Remove Value "+removeValue);
System.out.println("Remove1 "+remove1);
System.out.println("Remove2 "+remove2);
System.out.println("Remove3 "+remove3);
System.out.println("ArrayList Data after "+arrayList);
//Ged data from ArrayList
System.out.println("-- Example for Get Value from ArrayList --");
System.out.println("Get ArrayList value: "+arrayList.get(0));
System.out.println("Contains ArrayList: "+arrayList.contains("value1"));
System.out.println("Contains ArrayList: "+arrayList.contains("value3"));
//Loop data from Array List
System.out.println("-- Example for Iterate list from ArrayList --");
Iterator it=arrayList.iterator();
while(it.hasNext()){
String value=it.next();
System.out.println("List Iterated Value: "+value);
}
System.out.println("-- Example for Loop from ArrayList --");
for (String temp:arrayList){
System.out.println("For value ArrayList "+temp);
}
}
public static void main (String args[]){
//Test the code in main method
ArrayListExample arryList=new ArrayListExample();
arryList.arrayListExample();
}
}
Test Result in below
ArrayList Data befor [value1, value2, value3, value4, value5]
Remove Value value3
Remove1 true
Remove2 false
Remove3 true
ArrayList Data after [value4, value5]
-- Example for Get Value from ArrayList --
Get ArrayList value: value4
Contains ArrayList: false
Contains ArrayList: false
-- Example for Iterate list from ArrayList --
List Iterated Value: value4
List Iterated Value: value5
-- Example for Loop from ArrayList --
For value ArrayList value4
For value ArrayList value5