Collections
Tags: #◇Computer Science #◇CCPROG3 #◇Collections #◇Code Snippets #◇M4
◇Key Definitions
The Java Collections Framework is a unified architecture for representing and manipulating collections (groups of objects). It contains interfaces, implementations, and algorithms.
◇Theoretical Framework
Core interfaces include:
List: An ordered collection (e.g., ArrayList, LinkedList). Can contain duplicates.
Set: A collection that cannot contain duplicate elements (e.g., HashSet, TreeSet).
Map: An object that maps keys to values (e.g., HashMap, TreeMap). Cannot contain duplicate keys.
◇Code Implementation
import java.util.*;
public class CollectionExample {
public static void main(String[] args) {
// List Example
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
// Set Example
Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(1); // Ignored
// Map Example
Map<String, Integer> map = new HashMap<>();
map.put("Alice", 90);
map.put("Bob", 85);
}
}
◇Syntax Breakdown
<Type>: Generics are used to specify the type of objects the collection will hold, ensuring type safety at compile time.
new ArrayList<>(): The diamond operator <> infers the generic type from the variable declaration.
◇Complexity Analysis
| Collection | Add | Remove | Contains |
|---|---|---|---|
ArrayList | O(1) am. | O(n) | O(n) |
LinkedList | O(1) | O(1)* | O(n) |
HashSet | O(1) | O(1) | O(1) |
TreeSet | O(log n) | O(log n) | O(log n) |
HashMap | O(1) | O(1) | O(1) |
◇References & Navigation
- Previous Topic: ◇Class Relationships
- Next Topic: ◇Inheritance
- Related Notes: ◇Overview of Programming Languages
ACTIVE RECALL VERIFICATION
Select an answer to verify conceptual comprehension and reveal the technical rationale.
What is the primary purpose of the Java Collections Framework?
Which core interface in the Collections Framework cannot contain duplicate elements?
In the context of a Map, which of the following is true?
What is the amortized time complexity for adding an element to an ArrayList?
What does the diamond operator <> do in the statement List<String> list = new ArrayList<>();?