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:
add(E e)
: Adds an element to the collection.remove(Object o)
: Removes a single instance of the element if present.contains(Object o)
: Checks if an element is present.size()
: Returns the number of elements.clear()
: Removes all elements.iterator()
: Obtains an iterator to traverse elements.Example:
Collection<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
System.out.println(fruits); // Output: [Apple, Banana]
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]
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:
LinkedHashSet
).Example:
Set<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple"); // Duplicate ignored
System.out.println(fruits); // Output: [Apple, Banana]
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