Learnings

  • Like an array but length is variable
  • Must sue wrapper class
  • Works with enhanced loops

Wrapper Classes

  • Used with arraylist for primitives
  • Java auto converts between wrappers and primitives
// Integer wrapper class
ArrayList<Integer> listOfIntegers = new ArrayList<>();

listOfIntegers.add(new Integer(10));

// automatically converts to Integer
listOfIntegers.add(1);

// using toString method of ArrayList
System.out.println(listOfIntegers);
[10, 1]

Hack 1

// HACK!!!!
// Create an arrayList and use one of the cool methods for it

import java.util.ArrayList; 
import java.lang.Math;

public class hack1 {
    public static void main (String[] args) {
        ArrayList<Integer> arr = new ArrayList<Integer>();
        arr.add(5);
        arr.add(4);
        arr.add(3);
        int min = 0;
        int max = arr.size();
        int range = max - min;
        
        for (int i = 0; i < 5; i++) {
            int rand = (int)(Math.random() * range) + min;
            System.out.println(arr.get(rand));
        }

       
    }
}

hack1.main(null);
4
4
4
5
5

Hack 2

import java.util.ArrayList;

public class main {
    public static void main(String[] args) {
        ArrayList<String> color = new ArrayList<String>(); 
        color.add("red apple");
        color.add("green box");
        color.add("blue water");
        color.add("red panda");


        for (int i = 0; i < color.size(); i++) {
            if(color.get(i).contains("red")) {
                color.remove(i);
            }
        }
        
        System.out.println(color);
    }
}


/*/ 
using 

if(color.get(i).contains("red"))

iterate through the arraylist and remove all elements that contain the word red in them
/*/
main.main(null);

Hack 3

// find the sum of the elements in the arraylist

ArrayList<Integer> num = new ArrayList<Integer>(); 

num.add(5);
num.add(1);
num.add(3);

public int sum = 0;

for (int i = 0; i<num.size(); i++) {
    sum = sum + num.get(i);
}

System.out.println(sum);