In Java, there are several ways to remove all elements from a Collection. Here are some examples:
Using the clear() method: The easiest way to remove all elements from a Collection is to use the clear() method, which removes all elements from the Collection. Here’s an example:
import java.util.ArrayList;
import java.util.Collection;
public class Example {
public static void main(String[] args) {
// create an ArrayList of strings
Collection<String> myCollection = new ArrayList<>();
myCollection.add("apple");
myCollection.add("banana");
myCollection.add("orange");
// remove all elements from the Collection
myCollection.clear();
// print out the contents of the Collection (should be empty)
System.out.println(myCollection);
}
}
In this example, we create an ArrayList of strings called "myCollection" and add three elements to it. We then use the clear() method to remove all elements from the Collection and use the toString() method to print out its contents, which should be empty.
Using the removeAll() method: Another way to remove all elements from a Collection is to use the removeAll() method with a Collection that contains all the elements to be removed. Here’s an example:
import java.util.ArrayList;
import java.util.Collection;
public class Example {
public static void main(String[] args) {
// create an ArrayList of strings
Collection<String> myCollection = new ArrayList<>();
myCollection.add("apple");
myCollection.add("banana");
myCollection.add("orange");
// create a Collection containing all elements to be removed
Collection<String> elementsToRemove = new ArrayList<>(myCollection);
// remove all elements from the Collection
myCollection.removeAll(elementsToRemove);
// print out the contents of the Collection (should be empty)
System.out.println(myCollection);
}
}
In this example, we create an ArrayList of strings called "myCollection" and add three elements to it. We then create another Collection called "elementsToRemove" containing all elements in "myCollection", and use the removeAll() method to remove all elements from "myCollection" that are also in "elementsToRemove". We use the toString() method to print out the contents of "myCollection", which should be empty.
In summary, there are several ways to remove all elements from a Collection in Java, including using the clear() method and using the removeAll() method with a Collection containing all elements to be removed. Which one to use depends on the specific use case and requirements of your program.