Overview:
Lesson 3 introduces the Collections Framework in Java, providing a powerful set of classes and interfaces for working with collections of objects. Collections allow developers to manage and manipulate groups of items efficiently. The main interfaces in the Collections Framework are List
, Set
, and Map
.
Key Concepts:
- Collections Framework:
- Definition: A unified architecture representing and manipulating collections of objects.
- Purpose: Provides a standard way to work with groups of objects, ensuring interoperability and ease of use.
- List Interface:
- Definition: An ordered collection (sequence) that allows duplicate elements.
- Common Implementations:
ArrayList
,LinkedList
,Vector
.
- Set Interface:
- Definition: An unordered collection that does not allow duplicate elements.
- Common Implementations:
HashSet
,LinkedHashSet
,TreeSet
.
- Map Interface:
- Definition: An object that maps keys to values, where each key must be unique.
- Common Implementations:
HashMap
,LinkedHashMap
,TreeMap
.
- Iterating and Manipulating Collections:
- Iteration using Iterators: Iterators provide a way to traverse through elements in a collection.
- Enhanced for loop: A concise way to iterate through elements introduced in Java 5.
- Common Operations: Adding, removing, and checking for the existence of elements.
Example:
Let’s create a program that demonstrates the use of the List
, Set
, and Map
interfaces in the Collections Framework. We’ll perform basic operations such as adding, removing, and iterating through elements.
import java.util.*;
public class CollectionsExample {
public static void main(String[] args) {
// List example
List<String> namesList = new ArrayList<>();
namesList.add("Alice");
namesList.add("Bob");
namesList.add("Charlie");
System.out.println("List Example:");
for (String name : namesList) {
System.out.println(name);
}
// Set example
Set<Integer> numbersSet = new HashSet<>();
numbersSet.add(1);
numbersSet.add(2);
numbersSet.add(3);
numbersSet.add(2); // Duplicate elements are not allowed
System.out.println("\nSet Example:");
for (int number : numbersSet) {
System.out.println(number);
}
// Map example
Map<String, Integer> ageMap = new HashMap<>();
ageMap.put("Alice", 25);
ageMap.put("Bob", 30);
ageMap.put("Charlie", 28);
System.out.println("\nMap Example:");
for (Map.Entry<String, Integer> entry : ageMap.entrySet()) {
System.out.println(entry.getKey() + " - Age: " + entry.getValue());
}
}
}
In this example, we use ArrayList
for the List
interface, HashSet
for the Set
interface, and HashMap
for the Map
interface. The program demonstrates adding elements, iterating through collections using different methods, and ensuring uniqueness in the Set
.