Lecture 13, CS 302-7 and 8, February 20
i. How deep can you go? Unlimited
i. This is the lot itself
i.
Type - eg
double, int
ii. Length – eg [10]
i. Element – item in a slot in the array, such as the car in a parking spot
ii. Index – [location]
1. the unique identifier for each spot in the array
i. int[] numbers=new int[10];
1. Note – initializes each value to 0
ii. int[] numbers;
numbers=new int[10];
iii. int[] numbers = {1,2,3,4,5,6,7,8,9,10};
1. Note – don’t need to ‘new’ it. Size is based on # of numbers in init
iv. Note – must do one of these before trying to access array elements. Otherwise error.
i. Arrays are references [pointers]
1. Kind of like how strings were pointers, ints etc weren’t [primitives]
i. int[] numbers={1,2,3,4};
ii. Get ‘2’ by doing numbers[1].
1. “numbers sub 1”
iii. Note – indexes must be integers. numbers[1.5] doesn’t make sense
1. Can still use literals, variables, constants, calculations, method calls (rand.nextInt(10)), etc (note – not every way)
iv. Array length
1. Similar to strings
2. Arrays run from index 0 to index (length-1)
v. Calculating array length:
1. numbers.length
2. Note – no () after length
3. This is different than string length, which is .length()
vi. int[x] is just an int – you can use it like any other int.
1. Printing, arithmetic, etc
i. Fixed length
1. Cannot be changed after you have initialized it
2. Can change after declaring, though.
Eg int[] numbers; //do stuff; numbers=new int[var];
ii. Error if try to access element outside of range
1. run-time, not compile time, so be careful!
2. So, if we do int[] numbers=new int[10];
If we try to get int[10], java crashes
iii. Note – the exception will tell us why/where it failed, which is good
iv. Can re-initialize using new, but not using {} shortcut
i. Lends itself nicely to for loops
ii.
For(int
i=0;i<array.length;i++)
1. remember that arrays run from 0 to length-1, so above makes sense
i. Example – PartArray.java
1. Use of sentinel – abort early