Lesson 7
Learnings
- Like an array but length is variable
- Must sue wrapper class
- Works with enhanced loops
- Used with arraylist for primitives
Key Learning on Wrapper Classes
- Used with arraylist for primitives
- Java auto converts between wrappers and primitives
- An ArrayList cannot directly represent primitive datatypes. In the above example, I wanted an ArrayList of integers. The datatype that I provide is not int - it is instead Integer.
- At a lower level, wrapper classes are classes that encapsulate data types, so that you can create objects of those datatypes. You can only have an ArrayList of objects, so this is one good use case for wrapper classes.
// 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);
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);
}
}
main.main(null);
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);