Unit 7 Work
Unit 7 CB
// 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);
Key Learning on Wrapper Classes
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.
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);
// 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);