RKTechGame | Java Collection Interfaces Detailed

Collection Interface

The Collection interface is the root interface in the Java Collections Framework hierarchy representing a group of objects known as elements.

It defines basic operations such as adding, removing, clearing, checking elements, and iteration. It extends the Iterable interface, enabling traversal of elements.

It has many implementations, but List, Set, and Queue are its main subinterfaces.

Common Methods:

Example:

Collection<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
System.out.println(fruits); // Output: [Apple, Banana]

List Interface

The List interface extends Collection and represents an ordered collection that allows duplicate elements.

Elements can be accessed by their integer index (position in the list). Common implementations include ArrayList, LinkedList, and Vector.

Key Features:

Frequently used implementations:

Example:

List<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Blue");
colors.add("Red");
System.out.println(colors); // Output: [Red, Blue, Red]

Set Interface

The Set interface extends Collection and represents an unordered collection that does not allow duplicate elements.

Common implementations include HashSet, LinkedHashSet, and TreeSet.

Key Features:

Example:

Set<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple"); // Duplicate ignored
System.out.println(fruits); // Output: [Apple, Banana]

Map Interface

The Map interface is part of the Java Collections Framework but is not a subinterface of Collection. It represents a collection of key-value pairs.

Keys must be unique, but values can be duplicated.

Common implementations include HashMap, TreeMap, and LinkedHashMap.

Key Features:

Example:

Map<String, String> capitals = new HashMap<>();
capitals.put("USA", "Washington DC");
capitals.put("India", "New Delhi");
System.out.println(capitals.get("India")); // Output: New Delhi