14. arrays i
TRANSCRIPT
From last time…• Please turn in Homework 2!
• We made a beautiful object-oriented night sky!
• Remember that a class has:!! 1. a name!! 2. attributes (variables)!! 3. a constructor (run via ‘new’)!! 4. and methods (actions)
Arrays I
CAP 3032
Rules of an Array• An array is a ordered “list” object which which
holds multiple “elements” (variables or objects)!
• It can hold only “elements” of one type!
• It cannot change size after it has been created!
• It starts at the 0th position!
• An array, like a variable, is declared & initialized
Memory
int x;
How does the compiler know!how much space to reserve?
MemoryType Bits Signed? Min Value Max Value
byte 8 Yes -128 127
short 16 Yes -32768 32767
int 32 Yes -2147483648 2147483647
long 64 Yes etc… etc…
char (UTF-16) 16 No 0 65535
Arrays…• are declared & initialized!
• are ordered!
• hold only elements of one type!
• cannot change size!
• start at 0!
• …why!? Because of memory management.
1. Array Declaration• Two parts: a type and a name (just like a variable)!
• Brackets after the variable type denote an array of that variable type:!
! int[] xpositions; // array of integers
float[] widths; // array of floats
// note that int != int[]
2. Array Initialization• An array is an object, so we use the new operator!
• Much like variables, we have to give the initial “state” of the array, which is the size:!
! xpositions = new int[42]; // empty array
widths = new float[78]; // empty array
// size must be an integer! new int[17.2]
1 & 2. One-line Array Creation
• Just like variables we can declare and initialize arrays in one line:!
int[] xpositions = new int[42];
float[] widths = new float[78];
• Compare to declaring & initializing primitives:! int xposition = 22;
float width = 32.5;
Getting an Element
To access an element in an array: !
arrayName[elementNumber]
int x = xpositions[0];
float myWidth = widths[13];
Setting an Element1. Set single elements:!! xpositions[0] = 13;
xpositions[1] = 26;
xpositions[2] = 39;
2. “Array Literal,” manually set elements:!! int[] xpositions = {13,26,39};
// this only works at initialization
Demo!Array Basics &!Star Coordinates
Iteration!• We can iterate through an array using a loop:!! for(int i = 0; i < arrayName.length; i++) {
arrayName[i] = 0; // sets each to 0
}
• We can also perform operations in the loop:!! for(int i = 0; i < arrayName.length; i++) {
arrayName[i] += 3; // increments each by 3
}
Demo!Drawing a Line
For next time…
• Friday: Quiz 3 (Function, Objects, & Arrays)!
• Monday: Iteration 1 Group Presentations!
• Read Shiffman, p. 153–162 (Arrays II)