The Collection interface in Java provides the foundation for several other important interfaces, such as List, Set, and Queue. It represents a group of objects that can be treated as a single unit.
Collection Interface Overview
The Collection interface defines a set of methods for adding, removing, and manipulating elements in the collection. It also includes methods for determining the size of the collection, checking if the collection contains a specific element, and iterating over the elements in the collection.
Some of the key methods defined in the Collection interface include:
- add(): Adds an element to the collection
- remove(): Removes an element from the collection
- size(): Returns the number of elements in the collection
- contains(): Returns true if the collection contains the specified element
- iterator(): Returns an iterator over the elements in the collection
Other interfaces like List, Set, and Queue extend the Collection interface and add additional functionality. For example, List allows for indexed access and maintains the order of the elements in the collection, while Set does not allow for duplicates.
Collection Interface Example
package com.java.collections.interfaces;
import java.util.ArrayList;
import java.util.Collection;
public class CollectionDemo {
public static void main(String[] args) {
Collection < String > fruitCollection = new ArrayList < > ();
fruitCollection.add("banana");
fruitCollection.add("apple");
fruitCollection.add("mango");
System.out.println(fruitCollection);
fruitCollection.remove("banana");
System.out.println(fruitCollection);
System.out.println(fruitCollection.contains("apple"));
fruitCollection.forEach((element) - > {
System.out.println(element);
});
fruitCollection.clear();
System.out.println(fruitCollection);
}
}
Here's a step-by-step explanation of what the program does:
- The
main
method creates a newArrayList
of strings calledfruitCollection
. - The
add
method is used to add three strings ("banana", "apple", and "mango") to thefruitCollection
. - The
println
method is used to print the entirefruitCollection
to the console. - The
remove
method is used to remove the string "banana" from thefruitCollection
. - The
println
method is used to print the updatedfruitCollection
to the console. - The
contains
method is used to check if thefruitCollection
contains the string "apple". The result is printed to the console. - The
forEach
method is used to iterate over each element in thefruitCollection
. For each element, theprintln
method is used to print the element to the console. - The
clear
method is used to remove all elements from thefruitCollection
. - The
println
method is used to print the emptyfruitCollection
to the console.
[banana, apple, mango]
[apple, mango]
true
apple
mango
[]
Comments
Post a Comment