Lecture 13, CS 302-6, October 3
i. How deep can you go? Unlimited
ii. 3-loop example: drawing 3d figures
i.
Type - eg
double, int
ii. Length – [10]
i. Element – [slot in the array – one item in the array]
ii. Index – [location 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 count 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, while ints weren’t [they are primitives]
ii. Not on tests: new allocates memory in heap
1. FYI: Dynamic memory allocation, garbage collection etc
2. rule of thumb – ‘new’ reserves space in memory
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
iv. Can still use literals, variables, constants, calculations, method calls (numbers[rand.nextInt(10)]), etc
v. Array length
1. Similar to string length
2. Arrays run from index 0 to index (length-1)
3. http://xkcd.com/163/
vi. Calculating array length:
1. numbers.length
2. Note – no () after length
vii. numbers[x] is just an int – can use it like any other int.
1. Printing, arithmetic, etc
i. Arrays lend themselves 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
1. Example – PartArray.java
i. Example – RefArray.java
i. int[] data = {…};
For( int value : data)
{
//body
}