Java.Collections.What is the difference between java.util.Collection and java.util.Collections?

The main difference is:

  • Collection<E> (Interface) → The root interface for all collections like List, Set, and Queue. It defines methods like add(), 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.util package.
  • 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.util package.
  • 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

FeatureCollection<E> (Interface)Collections (Utility Class)
TypeInterfaceClass
PurposeDefines collection behaviorProvides 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 UsageCollection<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 Collections when you need helper methods for modifying or processing collections.
This entry was posted in Без рубрики. Bookmark the permalink.