List clear/remove elements
In this chapter you will learn:
Clear a List
The clear methods from List is defined as follows:
void clear()
Removes all of the elements from this list (optional operation).
import java.util.ArrayList;
import java.util.List;
/* ja va2 s . c o m*/
public class Main {
public static void main(String[] args) {
List list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
list.add("java2s.com");
System.out.println("List has:" + list);
list.clear();
System.out.println("List has:" + list);
}
}
The output:
Remove element from List
The following methods remove elements from a List.
E remove(int index)
Removes the element at the specified position in this list (optional operation).boolean remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present (optional operation).boolean removeAll(Collection<?> c)
Removes from this list all of its elements that are contained in the specified collection (optional operation).boolean retainAll(Collection<?> c)
Retains only the elements in this list that are contained in the specified collection (optional operation).
import java.util.ArrayList;
import java.util.List;
/*ja v a 2 s .co m*/
public class Main {
public static void main(String[] args) {
List list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
list.add("java2s.com");
System.out.println(list);
list.remove("java2s.com");
System.out.println(list);
}
}
The output:
The the output we can see that the string 'java2s.com' is not in the list after being removed. And we removed a string by its value.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Collections