7.1: ArrayList Intro

  • ArrayLists are dynamic, meaning their size can grow or shrink as needed, but arrays are static in size
  • Instead of creating a different size array each time, while painstakingly copying the data from the initial array to the new one, we can use ArrayLists! Ex: You and ur beautiful wife have 8 kids and your house has 8 bedrooms… Screenshot 2024-09-18 at 8 05 02 PM

In order to use the ArrayList class, it needs to be imported from the java util package. This can be done by writing import java.util.ArrayList; at the beginning of the code

import java.util.ArrayList;

ArrayList objects are initialized the same way as most object classes. However, the element type (String, Integer, Boolean) must be specified in the <>. Look at the example below, where the element type is String in this case.

ArrayList<String> list = new ArrayList<String>();

ArrayLists can be created without specifying a type, allowing them to hold any object type. However, its better to define the type because it allows the compiler to catch errors at compile time whcich makes the code more efficient and easier to debug. Example is below

ArrayList list = new ArrayList();

Popcorn Hack #1

Create 2 ArrayLists, 1 called studentName and 1 called studentAge

import java.util.ArrayList;

public class ProductCatalog {

    public static void main(String[] args) {
        // what should go in the place of the question marks?
        List<?> productNames = new ArrayList<>(); 
        List<?> productPrices = new ArrayList<>();
    }
}