• Popcorn Hack #3 (Long)
  • Hard Hack: “Simple Inventory Manager”
  • 7.2: ArrayList Methods

    • Getting access to elements stored in an ArrayList can be done with iteration statements
    • This is called “traversing” the ArrayList

    Here are some useful ArrayList methods:

    • void add(int index, Object obj) - Inserts obj at the specified index, shifting elements at and above that position to the right, and increases the list’s size by one.

    • boolean add(Object obj) - Adds obj to the end of the list and returns true.

    • Object get(int index) - Retrieves the element located at the specified index.

    • int size() - Returns the total number of elements currently in the list.

    • Object set(int index, Object obj) - Replaces the element at index with obj and returns the element previously at that position.

    • Object remove(int index) - Deletes the element at index, shifts all subsequent elements to the left, and returns the removed element.

    Note on Arraylist<> (Specifying Elements)

    • When Arraylist is specified, then the code will only allow or return objects of that specific type
    • You don’t have to define an element, its just better to because the compiler will show an error and it’ll catch bugs easier

    Examples below!

    ArrayList<String> names = new ArrayList<>();  // Will only store Strings
    ArrayList<Integer> numbers = new ArrayList<>();  // Will only store Integers
    
    ArrayList<Integer> ages = new ArrayList<>();
    ages.add(25);    // Works fine
    ages.add("25");  // Compiler error because "25" is a String, not an Integer
    
    
    |   ages.add("25");  // Compiler error because "25" is a String, not an Integer
    
    incompatible types: java.lang.String cannot be converted to java.lang.Integer
    

    Size of the ArrayList

    • int size(); : returns the number of elements in the list

    Example below!

    ArrayList<Integer> a1 = new ArrayList<>();
    a1.add(10);
    a1.add(20);
    a1.add(30);
    
    System.out.println(a1.size()); 
    
    
    3
    

    Adding Items to an ArrayList

    • boolean add(Object obj); : adds obj to the end of the `rrayList and returns true
    • void add(int index, Object obj) : inserts obj at the specified index and if the index is valid, it shifts all the elements to the right from that position and increases the size of the Arraylist (wow i bet arrays cant do that!)

    example below!

    ArrayList<Double> numbers = new ArrayList<>();
    numbers.add(5.5);
    numbers.add(7.2);
    numbers.add(9.8);
    
    numbers.add(1, 6.3);  // inserts 6.3 at index 1
    
    System.out.println(numbers);
    
    
    [5.5, 6.3, 7.2, 9.8]
    

    Screenshot 2024-10-03 at 10 17 22 PM

    Popcorn Hack #3 (Long)

    • Step 1: Declare and Initialize

    Create an ArrayList that stores Double values, called scores.

    • Step 2: Add Elements

    Add the following values to your scores list: 85.6, 92.4, 78.9, 88.1. Print the size of the list after adding these elements

    • Step 3: insert at index

    use the add(int index, Double obj) method to insert the value 90.0 at index 2. Print the list to verify the insertion.

    • Step 4: Remove an Element

    Remove the element at index 3 using remove(int index). Print the list to see the updated values.

    • Step 5: Get and Set

    Retrieve the element at index 1 and print it. Then, use set(int index, Double obj) to update the element at index 0 to 91.5. Print the list after the modification.

    Deleting Items from an ArrayList

    E remove(int index) : Deletes the element at the specified index and shifts all elements after that index one position to the left. it reduces the size of the arraylist by 1. (also returns element thats removed when used)

    ArrayList<String> cars = new ArrayList<>();
    cars.add("MortMobile");
    cars.add("Lopez Lambo");
    cars.add("Jonathan Jeepatron");
    cars.add("Cybertruck");
    
    // prints the initial list of cars
    System.out.println("initial cars list: " + cars);
    
    // removing the car at index 2 (Jonathan Jeepatron)
    cars.remove(2);
    
    // prints updated list of cars after deletion (rip jonathan jeepatron)
    System.out.println("updated cars list: " + cars);
    
    
    initial cars list: [MortMobile, Lopez Lambo, Jonathan Jeepatron, Cybertruck]
    updated cars list: [MortMobile, Lopez Lambo, Cybertruck]
    

    Updating Items in an ArrayList

    To update variables or object properties in Java, simply assign new values using the = operator or update object fields through methods. Make sure the data types match and understand how scopes affect where updates can occur.

    import java.util.ArrayList;
    
    ArrayList<String> fruits = new ArrayList<>();
    
    
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");
    
    System.out.println("Original list: " + fruits);
    
    
    fruits.set(1, "Grapes");
    
    
    System.out.println("Updated list: " + fruits);
    
    Original list: [Apple, Banana, Orange]
    Updated list: [Apple, Grapes, Orange]
    

    Popcorn hack

    You have an ArrayList that contains the names of 5 cities:

    ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
    
    Write a Java program to update the third city (index 2) to "San Francisco" using the set() method, and then print the updated list.
    
    
    
    ```java
    
    
    import java.util.ArrayList;
    
    
    ArrayList<_____> cities = new ArrayList<>();
    cities.add("New York");
    cities.add("Los Angeles");
    cities.add("Chicago");
    cities.add("Houston");
    cities.add("Phoenix");
    
    
    System.out.println(cities);
    

    Expected Output: [New York, Los Angeles, San Francisco, Houston, Phoenix]

    Accessing Items in an ArrayList

    In Java, you can access items in an array by using the index of the element, with array indices starting from 0. For example, array[0] will access the first element, and array[2] will access the third element. You can use a loop, such as a for or while loop, to iterate through all the elements of the array.

    
    import java.util.ArrayList;
    
    ArrayList<Integer> numbers = new ArrayList<>();
    
    numbers.add(10);
    numbers.add(20);
    numbers.add(30);
    numbers.add(40);
    
    int firstNumber = numbers.get(0);  
    int thirdNumber = numbers.get(2);  
    
    
    System.out.println("First number: " + firstNumber);
    System.out.println("Third number: " + thirdNumber);
    
    First number: 10
    Third number: 30
    

    Passing an ArrayList as a Method Parameter

    The only time that it is wise to use ArrayList instead of ArrayList<E> is when it is as a function parameter and it is only using ArrayList<>.get(E) or ArrayList<>.size(). Consider the following code:

    
    import java.util.ArrayList;
    
    public class Main {
    
        public static void main(String[] args) {
            // Create an ArrayList of strings
            ArrayList<String> animals = new ArrayList<>();
            animals.add("Dog");
            animals.add("Cat");
            animals.add("Elephant");
    
            printArrayList(animals);
        }
        
        public static void printArrayList(ArrayList<String> list) {
            System.out.println("ArrayList Elements:");
            for (String element : list) {
                System.out.println(element);
            }
        }
    
    
    }
    
    Main.main(null);
    
    ArrayList Elements:
    Dog
    Cat
    Elephant
    

    Returning an ArrayList from a Method

    In order for you to return an ArrayList, the data type must be specified, and the return type must be the same as the return value. Consider the following code:

    
    import java.util.ArrayList;
    
    public class Main {
    
        public static ArrayList<String> createAnimalList() {
            ArrayList<String> animals = new ArrayList<>();
            animals.add("Lion");
            animals.add("Tiger");
            animals.add("Elephant");
            return animals;
        }
    
        public static void main(String[] args) {
            ArrayList<String> animalList = createAnimalList();
    
            System.out.println("Returned ArrayList: " + animalList);
        }
    }
    
    Main.main(null);
    
    Returned ArrayList: [Lion, Tiger, Elephant]
    

    Hard Hack: “Simple Inventory Manager”

    Problem Statement:

    You are building a basic inventory system using Java’s ArrayList to manage a list of items in a store. You will implement functions to add, update, delete, and view items in the inventory.

    Starting Inventory:
    The inventory already contains the following items:

    • "Laptop", "Mouse", "Keyboard"

    Your task is to:

    1. Add items to the inventory.
    2. Update an item at a specific position in the inventory.
    3. Delete an item from the inventory.
    4. View all the items currently in the inventory.

    Directions:

    1. Create an ArrayList called inventory that holds strings representing the items.
    2. Implement the following methods:
      • addItem(ArrayList<String> inventory, String item): Adds an item to the inventory.
      • updateItem(ArrayList<String> inventory, int index, String newItem): Updates the item at the specified index.
      • deleteItem(ArrayList<String> inventory, int index): Deletes the item at the specified index.
      • viewInventory(ArrayList<String> inventory): Displays all the items in the inventory.
    3. In your main() method:
      • Initialize the inventory with the starting items.
      • Add one new item to the inventory.
      • Update the second item.
      • Delete the third item.
      • Display the final inventory.

    Example Workflow:

    1. Start with the inventory: ["Laptop", "Mouse", "Keyboard"].
    2. Add "Monitor".
    3. Update "Mouse" to "Gaming Mouse".
    4. Delete "Keyboard".
    5. Display the final inventory.

    Expectations:

    • Ensure valid index when updating or deleting items (handle out-of-bounds indices).
    • Use the get(), set(), add(), and remove() methods to manage the ArrayList.
    • After all operations, print the final version of the inventory using viewInventory().

    Starter Code

    import java.util.ArrayList;
    
    public class InventoryManager {
    
        // Method to add an item to the inventory
        public static void addItem(ArrayList<String> inventory, String item) {
            inventory.add(item);
        }
    
        // Method to update an item at a specific index in the inventory
        public static void updateItem(ArrayList<String> inventory, int index, String newItem) {
            if (index >= 0 && index < inventory.size()) {
                inventory.set(index, newItem);
            } else {
                System.out.println("Invalid index. Cannot update.");
            }
        }
    
        // Method to delete an item from the inventory
        public static void deleteItem(ArrayList<String> inventory, int index) {
            if (index >= 0 && index < inventory.size()) {
                inventory.remove(index);
            } else {
                System.out.println("Invalid index. Cannot delete.");
            }
        }
    
        // Method to display all items in the inventory
        public static void viewInventory(ArrayList<String> inventory) {
            System.out.println("Current Inventory: " + inventory);
        }
    
        public static void main(String[] args) {
            // Initialize the inventory with starting items
            ArrayList<String> inventory = new ArrayList<>();
            inventory.add("Laptop");
            inventory.add("Mouse");
            inventory.add("Keyboard");
    
            // Add a new item
            addItem(inventory, "Monitor");
    
            // Update the second item
            updateItem(inventory, 1, "Gaming Mouse");
    
            // Delete the third item
            deleteItem(inventory, 2);
    
            // View the final inventory
            viewInventory(inventory);
        }
    }