Unit 7 - ArrayList
Arraylist
// 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);
// 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);
}
}
/*/
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);