Junior
What is the difference between java.util.Collection and java.util.Collections?
sobes.tech AI
Answer from AI
java.util.Collection is the root interface of the collection hierarchy. It defines the basic operations available for all collections (adding, removing, checking for elements, etc.).
java.util.Collections is a utility class that contains static methods for performing various operations on collections (sorting, searching, changing order, creating unmodifiable views, etc.).
Here are the key differences in the form of a table:
| Characteristic | java.util.Collection |
java.util.Collections |
|---|---|---|
| Type | Interface | Class |
| Purpose | Defines the contract for collections | Provides utility methods |
| Usage | Implemented by collection classes | Used for manipulating collections |
| Object creation | No (interface) | Instances are not created (static methods) |
Example of using Collections:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
//
List<String> names = new ArrayList<>();
names.add("Bob");
names.add("Alice");
names.add("Charlie");
// Sorting the list
Collections.sort(names);
System.out.println(names); // Output: [Alice, Bob, Charlie]
// Creating an unmodifiable list
List<String> unmodifiableNames = Collections.unmodifiableList(names);
// unmodifiableNames.add("David"); // Will throw UnsupportedOperationException