ArrayList clear/remove
In this chapter you will learn:
Clear an ArrayList
void clear()
Removes all of the elements from this list.
import java.util.ArrayList;
/*from ja va 2 s. c om*/
public class Main {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String>();
al.add("C");
al.add("A");
al.add("E");
al.add("java2s.com");
al.add("D");
al.add("F");
al.add(1, "java2s.com");
System.out.println(al);
al.clear();
System.out.println(al);
}
}
The output:
Remove from ArrayList
The following two methods remove elements from an ArrayList.
E remove(int index)
Removes the element at the specified position in this list.booleanremove(Object o)
Removes the first occurrence of the specified element from this list, if it is present.
import java.util.ArrayList;
//j a v a 2s.c o m
public class MainClass {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " + al.size());
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
System.out.println("Contents of al: " + al);
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
The output:
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Collections