Thursday, September 1, 2011

Arraylist example in java


//ArrayListExample1.java
import java.util.ArrayList;
//import java.util.List;
import java.util.Iterator;

public class ArrayListExample1
{
public static void main(String a[])
{
ArrayList arrayList = new ArrayList();
//List arrayList = new ArrayList();

for(int i=1;i<=5;i++)
{
//add element in ArrayList
arrayList.add(i);
}

System.out.println("Initially ArrayList value is as follows:");
Iterator it1 = arrayList.iterator();
while (it1.hasNext())
{
System.out.println(it1.next());
}

//remove element from ArrayList index 2 and 3 which start from index o
System.out.println("Remove element form index 2,3 whose vlues are "+arrayList.get(2)+" and "+arrayList.get(3)+" respectively");

Object index2value = arrayList.get(2);
Object index3value = arrayList.get(3);

arrayList.remove(index2value);
arrayList.remove(index3value);
/* If we simply use "arrayList.remove(2); and then arrayList.remove(3);" then after removing element form index 2 list length
* decrease and "arrayList.remove(3)" delete the element form the new list i.e. not value 4 it is the new value 5.
* To solve this problem we have to do the above four steps.
*/

System.out.println("After removing element form index 2 and 3 the ArrayList's value is as follows:");
Iterator it2 = arrayList.iterator();
while (it2.hasNext())
{
System.out.println(it2.next());
}
}
}

Output =>

Initially ArrayList value is as follows:
1
2
3
4
5
Remove element form index 2,3 whose vlues are 3 and 4 respectively
After removing element form index 2 and 3 the ArrayList's value is as follows:
1
2
5

No comments:

Post a Comment