1. Introduction
In Java, Iterable and Collection are two fundamental interfaces that are a part of the Java Collections Framework. The Iterable interface is the root interface for all the collection classes and provides the ability to iterate over a collection of objects. On the other hand, Collection extends Iterable and is the root interface of the collection hierarchy, representing a group of objects known as its elements.
2. Key Points
1. Iterable interface is primarily for implementing the "foreach" loop, and it defines only one method: iterator().
2. Collection interface includes all the functionality of Iterable, and adds methods to add, remove, and check the size of the collection, among others.
3. Every Collection is Iterable, but not all Iterables are Collections.
4. Iterable can be seen as a more general concept that allows an object to be the target of the "enhanced for loop" (for-each loop).
3. Differences
Iterable | Collection |
---|---|
Minimal functionality for object iteration. | Rich set of methods for manipulating a collection of objects. |
Defines a single iterator() method. | Includes methods like add(), remove(), size(), isEmpty(), and more. |
Does not imply data structure or collection of elements. | It is a data structure and implies a collection of elements. |
4. Example
// Importing necessary classes
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;
public class IterableVsCollection {
public static void main(String[] args) {
// Step 1: Create a Collection (ArrayList in this case)
Collection<String> collection = new ArrayList<>();
// Step 2: Add elements to the collection
collection.add("Java");
collection.add("Python");
collection.add("C++");
// Step 3: Iterate through the collection using Iterable interface
Iterator<String> iterator = collection.iterator();
while(iterator.hasNext()) {
String language = iterator.next();
System.out.println(language);
}
// Step 4: Use Collection methods directly
System.out.println("Total languages: " + collection.size());
System.out.println("Is Python in collection? " + collection.contains("Python"));
}
}
Output:
Java Python C++ Total languages: 3 Is Python in collection? true
Explanation:
1. An ArrayList instance is created which is a type of Collection.
2. Elements are added to the collection using Collection methods.
3. An iterator is obtained from the collection using the Iterable interface's iterator() method, and each element is printed.
4. Other Collection methods are used directly to display the size and check for an element's presence.
5. When to use?
- Use Iterable when you want to enable iteration over a collection of items using the for-each loop, without the need for collection-specific functionality.
- Use Collection when you need a full-fledged collection that supports direct manipulation like adding, removing items, and querying its size.
Comments
Post a Comment
Leave Comment