The main difference is:
Collection<E>(Interface) → The root interface for all collections likeList,Set, andQueue. It defines methods likeadd(),remove(),size(), etc.Collections(Utility Class) → A helper class that contains static methods for working with collections (e.g.,sort(),reverse(),shuffle(),unmodifiableList()).
1. Collection<E> (Interface)
- Belongs to
java.utilpackage. - Defines the core behavior for all collection types (
List,Set,Queue). - Implemented by classes like
ArrayList,HashSet,LinkedList, etc.
Example: Using Collection
import java.util.*;
public class Main {
public static void main(String[] args) {
Collection<String> names = new ArrayList<>(); // Using Collection reference
names.add("Alice");
names.add("Bob");
System.out.println(names); // Output: [Alice, Bob]
}
}
✅ Collection acts as a superinterface for collection types.
2. Collections (Utility Class)
- Contains only static methods to operate on collections.
- Belongs to
java.utilpackage. - Provides helper methods for sorting, searching, synchronization, and creating unmodifiable collections.
Example: Using Collections.sort()
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(5, 3, 9, 1));
Collections.sort(numbers); // Sorts the list in ascending order
System.out.println(numbers); // Output: [1, 3, 5, 9]
}
}
✅ Collections provides utility methods to work with collections.
3. Key Differences
| Feature | Collection<E> (Interface) | Collections (Utility Class) |
|---|---|---|
| Type | Interface | Class |
| Purpose | Defines collection behavior | Provides utility methods for collections |
| Contains Methods? | ✅ Yes (add, remove, size, etc.) | ✅ Yes (sort, reverse, shuffle, etc.) |
| Implements? | ❌ No, it’s an interface | ❌ No, it’s a utility class |
| Instantiable? | ❌ No (Interfaces cannot be instantiated) | ❌ No (Only static methods) |
| Example Usage | Collection<String> list = new ArrayList<>(); | Collections.sort(list); |
4. When to Use What?
- Use
Collection<E>when defining variables or working with generic data structures (List,Set,Queue). - Use
Collectionswhen you need helper methods for modifying or processing collections.