7.1: ArrayList Intro

  • ArrayLists are dynamic (size can grow and shrink unlike arrays which are static)
  • Instead of creating a different size array each time, we can use ArrayLists!
  • Ex: You and ur beautiful wife…

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

  • To use Arraylist class, it needs to be imported from java.util package
  • At beginning of code using an Arraylist, type the command below!
import java.util.ArrayList;

// your amazing code here!

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 objects are initialized like most object classes
  • the element type must be initialized in <>
  • The objects can’t store primitive types directly
ArrayList<String> bobtheminion = new ArrayList(); // example of initializing an arraylist of strings called "awesomeword"
ArrayList<Integer> bobtheminionage = new ArrayList<>();
ArrayList<Boolean> isbobtheminionavailable = new ArrayList<>(); 
ArrayList<Double> minionheights = new ArrayList<>();

Popcorn Hack #1

What’s wrong with the code below?

import java.util.ArrayList;

ArrayList<String> awesomeword = new ArrayList(); 
ArrayList<Int> coolnumbers = new ArrayList();
ArrayList<Boolean> truefalse = new ArrayList();
// change code and comment what you changed when doing homework

Screenshot 2024-09-24 at 8 12 38 PM

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

  • Arraylists can be created without specifying a type (they can hold any)
  • Better to define the type as it makes code easier to debug and more efficient
ArrayList list = new ArrayList(); // no object type specified!

Popcorn Hack #2

Create two ArrayList objects, one for storing integers (called sritestgrades) and another for storing strings (called srishobbies).

import java.util.ArrayList;

        // ur code here
        
        sritestgrades.add(45);
        sritestgrades.add(32);
        sritestgrades.add(1);
        sritestgrades.add(90);
        sritestgrades.add(74);
        
        srishobbies.add("watching netflix");
        srishobbies.add("sleeping");
        srishobbies.add("");
        srishobbies.add("annoying saathvik");
        
        // Printing the values
        System.out.println("Sri's horrible test grades are: " + sritestgrades);
        System.out.println("Sri's hobbies are: " + srishobbies);

Screenshot 2024-09-24 at 8 13 10 PM