Arrays and ArrayLists

Array- data structure used to implement a list object of the same type

  • object: passing through parameters = elements of the array can be accessed/modified

    • why? no copy of the array is made

    • can’t print it or will produce symbols

  • size can’t be changed

    • If attempted: it reassigns that array with a NEW array

  • automatic initialization

    • zero

    • false

    • null

Initialization

double [] data = new double[25];
double data [] = new double[25];
double [] data; 
data = new double [25];

Declaration

data[1] = 5.0; data[2] = 6.0;
double [] data = {5.0, 6.0};

Length

  • name.length (no parentheses bc it’s not a method)

Traversing

  • accessing: arr[i]

enhanced for loop: accessing elements only

int count = 0;
for (int num: arr){
	if (num % 2 == 0){
		count++;
	}
}
/counts even num

for loop: accessing, replacing, removing, etc

for (int i = 0; i < arr.length; i++){
	arr [i] = 0;
}
/all elements become 0

swap algorithm

public static void swap (int [] arr, int i, int j){
	int temp = arr[i]; //stores a value so it doesn't matter after arr[i] changes
	arr[i] = arr[j]; 
	arr[j] = temp;
}

ArrayList

  • size can be changed

  • automatically shift elements

  • printing the ArrayList: prints all the elements

length: last slot

  • list.size() - 1

Initialization

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