Learning Objectives

Master Arrays

Learn array declaration, initialization, and manipulation

Collections Framework

Understand List, Set, Map, and Queue interfaces

Generics

Learn type-safe collections with generics

Data Operations

Master sorting, searching, and filtering operations

Introduction to Arrays

What are Arrays?

Arrays are fixed-size collections of elements of the same type. They provide fast access to elements using indices.

Arrays vs C

C

Arrays are just pointers; no bounds checking; manual memory management

Java

Arrays are objects with bounds checking; automatic memory management

Array Declaration and Initialization

Declaration

// Declare array
int[] numbers;
String[] names;

// Initialize with size
int[] scores = new int[5];
String[] colors = new String[3];

// Initialize with values
int[] primes = {2, 3, 5, 7, 11};
String[] fruits = {"Apple", "Banana", "Orange"};

Accessing Elements

int[] numbers = {10, 20, 30, 40, 50};

// Access elements (0-based indexing)
int first = numbers[0];    // 10
int third = numbers[2];    // 30
int last = numbers[4];     // 50

// Modify elements
numbers[1] = 25;
numbers[3] = 45;

Array Properties

int[] numbers = {1, 2, 3, 4, 5};

// Get array length
int length = numbers.length;  // 5

// Iterate through array
for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}

// Enhanced for loop (for-each)
for (int num : numbers) {
    System.out.println(num);
}

Multidimensional Arrays

Java supports arrays with multiple dimensions.

// 2D array (matrix)
int[][] matrix = new int[3][4];

// Initialize 2D array
int[][] grid = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

// Access elements
int element = grid[1][2];  // 6

// Iterate through 2D array
for (int i = 0; i < grid.length; i++) {
    for (int j = 0; j < grid[i].length; j++) {
        System.out.print(grid[i][j] + " ");
    }
    System.out.println();
}

Collections Framework

What is Collections Framework?

The Collections Framework provides a unified architecture for representing and manipulating collections of objects.

Collection Hierarchy

Collection<E>

List<E>
Set<E>
Queue<E>

Map<K,V>

HashMap<K,V>
TreeMap<K,V>
LinkedHashMap<K,V>

Main Collection Types

List Interface

Ordered collections that allow duplicate elements.

// ArrayList - dynamic array
List names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");

// LinkedList - doubly-linked list
List numbers = new LinkedList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);

// Access elements
String first = names.get(0);  // "Alice"
names.set(1, "Robert");       // Replace "Bob" with "Robert"

Set Interface

Collections that do not allow duplicate elements.

// HashSet - unordered, no duplicates
Set uniqueNames = new HashSet<>();
uniqueNames.add("Alice");
uniqueNames.add("Bob");
uniqueNames.add("Alice");  // Won't be added (duplicate)

// TreeSet - ordered, no duplicates
Set sortedNumbers = new TreeSet<>();
sortedNumbers.add(30);
sortedNumbers.add(10);
sortedNumbers.add(20);
// Will be stored as: 10, 20, 30

Map Interface

Collections that map keys to values.

// HashMap - key-value pairs
Map ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
ages.put("Charlie", 28);

// Access values
int aliceAge = ages.get("Alice");  // 25

// Check if key exists
if (ages.containsKey("Bob")) {
    System.out.println("Bob's age: " + ages.get("Bob"));
}

Generics

What are Generics?

Generics provide type safety by allowing you to specify the type of objects that a collection can hold.

Type Safety

// Without generics (raw types) - NOT recommended
List rawList = new ArrayList();
rawList.add("Hello");
rawList.add(42);  // Mixed types allowed

// With generics - type safe
List stringList = new ArrayList<>();
stringList.add("Hello");
stringList.add("World");
// stringList.add(42);  // Compile-time error!

Generic Classes

You can create your own generic classes.

public class Box {
    private T content;
    
    public void put(T item) {
        this.content = item;
    }
    
    public T get() {
        return content;
    }
}

// Usage
Box stringBox = new Box<>();
stringBox.put("Hello");
String message = stringBox.get();

Box intBox = new Box<>();
intBox.put(42);
Integer number = intBox.get();

Practical Examples

Student Grade Management

import java.util.*;

public class GradeManager {
    private Map> studentGrades;
    
    public GradeManager() {
        studentGrades = new HashMap<>();
    }
    
    public void addGrade(String studentName, int grade) {
        studentGrades.computeIfAbsent(studentName, k -> new ArrayList<>()).add(grade);
    }
    
    public double getAverageGrade(String studentName) {
        List grades = studentGrades.get(studentName);
        if (grades == null || grades.isEmpty()) {
            return 0.0;
        }
        
        return grades.stream()
                   .mapToInt(Integer::intValue)
                   .average()
                   .orElse(0.0);
    }
    
    public List getTopStudents(int topCount) {
        return studentGrades.entrySet().stream()
                .sorted((e1, e2) -> 
                    Double.compare(getAverageGrade(e2.getKey()), 
                                 getAverageGrade(e1.getKey())))
                .limit(topCount)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
    }
}

Key Differences from C

Concept C Java
Arrays Pointers with manual memory management Objects with automatic memory management
Bounds Checking No bounds checking Runtime bounds checking
Collections Manual implementation needed Built-in Collections Framework
Type Safety No type safety Generics provide type safety
Dynamic Sizing Manual reallocation Automatic resizing (ArrayList)
Data Structures Manual implementation Built-in implementations

Summary

In this module, you've learned:

  • ? Array declaration, initialization, and manipulation
  • ? Multidimensional arrays and array properties
  • ? Collections Framework hierarchy and interfaces
  • ? List, Set, and Map implementations
  • ? Generics for type-safe collections
  • ? Practical applications with collections
  • ? Key differences between Java and C arrays/collections

Next Steps

  1. Complete the exercises in the exercises.md file
  2. Practice working with arrays and collections
  3. Move to Module 7: Exception Handling

?? Module 6 Complete!

You now have a solid understanding of arrays and collections. Time to learn about exception handling!