As we have seen the implementations of a List are :
Let us see the ArrayList implementation first.
Let us say, we have a List that contains three names, Mohan, Kriti and Salim. And we want to remove Kriti from the List.
It can be done with the remove() Method
import java.util.ArrayList; import java.util.List; public class MyApplication { public static void main(String[] args) { Listx = new ArrayList<>(); x.add("Mohan"); x.add("Kriti"); x.add("Salim"); x.remove("Kriti"); for (String data : x) { System.out.println(data); } } }
So, in the above code we have created a List,
Listx = new ArrayList<>();
And initialised three names to the variable x,
x.add("Mohan"); x.add("Kriti"); x.add("Salim");
Below is how the values are positioned in the List,
Next, we have used the remove() method that searches for the name Kriti and removes it from the List.
x.remove("Kriti");
Let us say, we have a List that contains three names, Mohan, Kriti and Salim. And we want to remove the element at index/position 2 from the List.
So, we can use remove() method again to remove an element from the List.
import java.util.ArrayList; import java.util.List; public class MyApplication { public static void main(String[] args) { Listx = new ArrayList<>(); x.add("Mohan"); x.add("Kriti"); x.add("Salim"); x.remove(2); for (String data : x) { System.out.println(data); } } }
So, in the above code we have created a List and initialised to the variable x.
Listx = new ArrayList<>(); x.add("Mohan"); x.add("Kriti"); x.add("Salim");
Below is how the values are positioned in the List,
Next, we have used the remove() method that searches for the element at index/position 2 and removes it from the List.
x.remove(2);
And as we can see, there is Salim at index/position 2. So Salim is removed from the List.
And we get the below output,
The removeAll() Method can be used to remove all the elements from the List.
import java.util.ArrayList; import java.util.List; public class MyApplication { public static void main(String[] args) { Listx = new ArrayList<>(); x.add("Mohan"); x.add("Kriti"); x.add("Salim"); x.removeAll(x); for (String data : x) { System.out.println(data); } } }
So, in the above code we have created a List and initialised to the variable x.
Listx = new ArrayList<>(); x.add("Mohan"); x.add("Kriti"); x.add("Salim");
Below is how the values are positioned in the List,
Next, we have used the removeAll() method that removes all the elements from the ArrayList making the List empty.
And we get an empty List as output,