Sobes.tech
Junior — Middle

What are the differences between the Collection and List interfaces in terms of their usage and capabilities?

sobes.tech AI

Answer from AI

The Collection interface in Java is the base interface for all collections, defining core operations such as adding, removing, checking for the presence of elements, etc. It does not guarantee the order of elements and does not provide methods for access by index.

List is a subinterface of Collection that represents an ordered collection (sequence). In a List, elements have an index, and you can access elements by position, insert or remove elements at specific positions.

Key differences:

  • Collection — a general interface for groups of objects, not necessarily ordered.
  • List — an ordered collection with index-based access and the ability to store duplicates.

Example:

Collection<String> coll = new ArrayList<>();
coll.add("A");
coll.add("B");

List<String> list = new ArrayList<>();
list.add("A");
list.add(0, "B"); // insert at index
String first = list.get(0); // access by index