Arrays
Collections
Arrays
4 7 3 12 -4 87 0 45
Arrays v. ArrayLists
Array | ArrayList |
Fixed Size | Grows and Shrinks |
All objects in collection the same type | All objects in collection the same type |
Weird syntax | Standard syntax |
No methods | Lots of methods |
Can quickly initialize | Must add objects one at a time |
Can use primitives or objects | Objects only - use wrapper classes for primitives |
Array types
Declare an array:
Car[] parkingLot;
int[] numbers;
String[] words;
Create arrays: Way 1
int[] numbers = new int[5];
Makes 5 empty “slots”, indexes are 0-4
String[] words = new String[10];
Car[] parkingLot = new Car[100];
Create arrays: Way 2
int[] numbers = {4,6,8,10,12};
String[] words = {“happy”, “go”, “lucky”};
Array Indices
4 7 3 12 -4 87 0 45
0 1 2 3 4 5 6 7
Array Indices
int x = nums[3];
nums[0] = -1*nums[0];
4 7 3 12 -4 87 0 45
0 1 2 3 4 5 6 7
Array Length
Access the length of any array with .length
int len = myNumbers.length;
No parentheses!!! Arrays don’t have methods.
Examples
Empty Arrays
What will print?
int[] nums = new int[10];
System.out.println(nums[5]);
What value is in the “empty” array?
Note - the length is 10, even though I haven’t set any of the values yet.
Initializing Arrays
Java zeroes out the memory in an array, so the value of the boxes in the empty array is whatever “0” means for your type:
int, double -> 0
boolean -> false
char -> some weird character
Objects -> NULL
Null Objects
Null Objects
String[] words = new String[3];
int length = words[0].length();
// CRASH!!
After making an array, make sure you initialize the objects inside the array
Visualizing an Array of Objects
Car[ ] myCars = new Car[5];
}
0 1 2 3 4
Ø Ø Ø Ø Ø
myCars
Tricky Stuff to Remember
int[ ] nums1 = {1,2,3};�int[ ] nums2 = nums1;
This doesn’t do it. It just gives 2 names for the same array
Tricky Stuff to Remember
More Exercises
public Student hasName(Student[] students, String name)
Multidimensional Arrays
0 1 2 3
� 0�� 1
Multidimensional Arrays
We visualize this
But it really is more like this
0 1 2 3
� 0�� 1
0 1
| | | |
| | | |
0 1 2 3
0 1 2 3
Multidimensional Arrays
arr.length gives the number of rows
arr[0].length gives the number of columns
arr[r][c] gives element at row r, column c
arr[r] gives the entire rth row
0 1
| | | |
| | | |
0 1 2 3
0 1 2 3
Initializing Shortcut
0 1 2 3
� 0�� 1
0 3 2 4�� 8 9 2 1
Multidimensional Arrays
0 1 2 3
� 0�� 1
2 3 -1 4�� 7 4 1 8
myNumbers
Array Patterns
for(int i = 0; i<array.length; i++){� int x = array[i];�}
for(int i = 0; i<array.length; i++){� for(int j = 0; j< array[i].length; j++){� int x = array[i][j];� }�}
Exercises
public int[][] multTable(int a, int b){
public int addUp(int[][]myTable){
public void findIndices(int target, int[][] table){