Remove all
elements from Java Array List
import
java.util.ArrayList;
public class
RemoveAllElementsOfArrayListExample
{
public static void
main(String[] args)
{
ArrayList arrayList =
new ArrayList();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
System.out.println("Size
of ArrayList before removing elements : "
+ arrayList.size());
arrayList.clear();
System.out.println("Size
of ArrayList after removing elements : "
+ arrayList.size());
}
}
Remove an element
from specified index of Java Array List
import
java.util.ArrayList;
public class
RemoveElementFromArrayListExample
{
public static void main(String[] args)
{
ArrayList arrayList =
new ArrayList();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
Object obj =
arrayList.remove(1);
System.out.println(obj
+ " is removed from ArrayList");
System.out.println("ArrayList
contains...");
for(int index=0; index
< arrayList.size(); index++)
System.out.println(arrayList.get(index));
}
}
Replace an
element at specified index of Java Array List
import
java.util.ArrayList;
public class
ReplaceElementAtSpecifiedIndexArrayListExample
{
public static void
main(String[] args)
{
ArrayList arrayList =
new ArrayList();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.set(1,"REPLACED
ELEMENT"); System.out.println("ArrayList contains...");
for(int index=0; index
< arrayList.size(); index++)
System.out.println(arrayList.get(index));
}
}
Search an element
of Java Array List
import java.util.ArrayList;
public class
SearchAnElementInArrayListExample
{
public static void
main(String[] args)
{
ArrayList arrayList =
new ArrayList();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
arrayList.add("1");
arrayList.add("2");
boolean blnFound =
arrayList.contains("2");
System.out.println("Does
arrayList contain 2 ? " + blnFound);
int index =
arrayList.indexOf("4");
if(index == -1)
System.out.println("ArrayList
does not contain 4");
else
System.out.println("ArrayList
contains 4 at index :" + index);
int lastIndex =
arrayList.lastIndexOf("1");
if(lastIndex == -1)
System.out.println("ArrayList
does not contain 1");
else
System.out.println("Last
occurrence of 1 in ArrayList is at index :"
+ lastIndex);
}
}
Sort elements of
Java Array List
import
java.util.ArrayList;
import
java.util.Collections;
public class SortJavaArrayListExample
{
public static void
main(String[] args)
{
ArrayList arrayList =
new ArrayList();
arrayList.add("1");
arrayList.add("3");
arrayList.add("5");
arrayList.add("2");
arrayList.add("4");
Collections.sort(arrayList);
System.out.println("ArrayList
elements after sorting in ascending order : ");
for(int i=0;
i
System.out.println(arrayList.get(i));
}
}
No comments:
Post a Comment