2.1.1 Collection Interfaces Explained
Collection interfaces in Java provide a framework for storing and manipulating groups of objects. Understanding these interfaces is crucial for effectively managing collections of data in Java SE 11.
Key Concepts
1. Collection Interface
The Collection
interface is the root interface of the collection hierarchy. It defines the basic operations that all collections should support, such as adding, removing, and querying elements.
Example
Collectioncollection = new ArrayList<>(); collection.add("Apple"); collection.add("Banana"); collection.remove("Apple"); System.out.println(collection); // Output: [Banana]
2. List Interface
The List
interface extends the Collection
interface and represents an ordered collection of elements. It allows duplicate elements and provides methods to access elements by their index.
Example
Listlist = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Cherry"); System.out.println(list.get(1)); // Output: Banana
3. Set Interface
The Set
interface also extends the Collection
interface and represents a collection of unique elements. It does not allow duplicate elements and does not guarantee any specific order.
Example
Setset = new HashSet<>(); set.add("Apple"); set.add("Banana"); set.add("Apple"); // Duplicate element, will not be added System.out.println(set); // Output: [Apple, Banana]
4. Queue Interface
The Queue
interface extends the Collection
interface and represents a collection designed for holding elements prior to processing. It follows the FIFO (First-In-First-Out) principle.
Example
Queuequeue = new LinkedList<>(); queue.add("Apple"); queue.add("Banana"); System.out.println(queue.poll()); // Output: Apple
5. Map Interface
The Map
interface is not a true collection, but it maps keys to values. It does not extend the Collection
interface but is part of the collection framework. It allows unique keys and can have duplicate values.
Example
Mapmap = new HashMap<>(); map.put("fruit1", "Apple"); map.put("fruit2", "Banana"); System.out.println(map.get("fruit1")); // Output: Apple
Examples and Analogies
Think of the Collection
interface as a general container for objects, similar to a box that can hold various items. The List
interface is like a numbered list where each item has a specific position.
The Set
interface is like a bag that can only hold one of each type of item, ensuring no duplicates. The Queue
interface is like a line at a store, where the first person in line is the first to be served.
The Map
interface is like a dictionary, where each word (key) has a definition (value) associated with it. By mastering these collection interfaces, you can efficiently manage and manipulate collections of data in your Java SE 11 applications.