Code-Alongs

About Code-Alongs

Code-alongs are guided coding sessions where you'll apply the concepts you've learned in the modules. These hands-on exercises will help you solidify your understanding of Lists, Big O notation, Comparable, and Comparators.

Work through these exercises with your instructor or on your own to gain practical experience with the concepts covered in this sprint.

Code-Along 1: Working with Lists

Objectives

  • Create and manipulate ArrayList objects
  • Implement common operations on lists (add, remove, find)
  • Iterate through lists using different techniques
  • Understand the performance implications of list operations

Sample Exercise: Shopping Cart Implementation

In this exercise, you'll implement a shopping cart system that allows users to:

  • Add items to a cart
  • Remove items from a cart
  • View all items in the cart
  • Calculate the total price

Implementation Guide

import java.util.ArrayList;
import java.util.List;

public class ShoppingCart {
    private List items;
    
    public ShoppingCart() {
        this.items = new ArrayList<>();
    }
    
    public void addItem(Item item) {
        items.add(item);
        System.out.println(item.getName() + " added to cart.");
    }
    
    public void removeItem(String itemName) {
        for (int i = 0; i < items.size(); i++) {
            if (items.get(i).getName().equals(itemName)) {
                Item removed = items.remove(i);
                System.out.println(removed.getName() + " removed from cart.");
                return;
            }
        }
        System.out.println("Item not found in cart.");
    }
    
    public void displayCart() {
        if (items.isEmpty()) {
            System.out.println("Your cart is empty.");
            return;
        }
        
        System.out.println("Items in cart:");
        for (Item item : items) {
            System.out.println("- " + item.getName() + ": $" + item.getPrice());
        }
        
        System.out.println("Total: $" + calculateTotal());
    }
    
    public double calculateTotal() {
        double total = 0;
        for (Item item : items) {
            total += item.getPrice();
        }
        return total;
    }
    
    public int getItemCount() {
        return items.size();
    }
}

Code-Along 2: Implementing Comparable and Comparators

Objectives

  • Implement the Comparable interface for natural ordering
  • Create custom Comparators for different sorting criteria
  • Use both approaches to sort collections
  • Understand when to use each approach

Sample Exercise: Book Library Sorting

In this exercise, you'll implement a Book class and various ways to sort books:

  • By title (natural ordering with Comparable)
  • By author (using a Comparator)
  • By publication year (using a Comparator)
  • By rating (using a Comparator)

Implementation Guide

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

// Book class with natural ordering by title
public class Book implements Comparable {
    private String title;
    private String author;
    private int year;
    private double rating;
    
    public Book(String title, String author, int year, double rating) {
        this.title = title;
        this.author = author;
        this.year = year;
        this.rating = rating;
    }
    
    // Getters
    public String getTitle() { return title; }
    public String getAuthor() { return author; }
    public int getYear() { return year; }
    public double getRating() { return rating; }
    
    @Override
    public String toString() {
        return title + " by " + author + " (" + year + ") - " + rating + " stars";
    }
    
    // Natural ordering by title
    @Override
    public int compareTo(Book other) {
        return this.title.compareTo(other.title);
    }
}

// Usage:
public class BookLibrary {
    public static void main(String[] args) {
        List books = new ArrayList<>();
        
        books.add(new Book("The Hobbit", "J.R.R. Tolkien", 1937, 4.7));
        books.add(new Book("1984", "George Orwell", 1949, 4.6));
        books.add(new Book("Pride and Prejudice", "Jane Austen", 1813, 4.5));
        
        // Sort by natural ordering (title)
        Collections.sort(books);
        System.out.println("Sorted by title:");
        displayBooks(books);
        
        // Sort by author
        Collections.sort(books, new AuthorComparator());
        System.out.println("\nSorted by author:");
        displayBooks(books);
        
        // Sort by year
        Collections.sort(books, new YearComparator());
        System.out.println("\nSorted by year:");
        displayBooks(books);
        
        // Sort by rating (descending)
        Collections.sort(books, new RatingComparator());
        System.out.println("\nSorted by rating (highest first):");
        displayBooks(books);
    }
    
    private static void displayBooks(List books) {
        for (Book book : books) {
            System.out.println(book);
        }
    }
}

// Comparators
class AuthorComparator implements Comparator {
    @Override
    public int compare(Book b1, Book b2) {
        return b1.getAuthor().compareTo(b2.getAuthor());
    }
}

class YearComparator implements Comparator {
    @Override
    public int compare(Book b1, Book b2) {
        return b1.getYear() - b2.getYear();
    }
}

class RatingComparator implements Comparator {
    @Override
    public int compare(Book b1, Book b2) {
        // Descending order (highest first)
        return Double.compare(b2.getRating(), b1.getRating());
    }
}