Topics Covered Arrays 1 D 2 D Passing











![Creating & Adding objects to an ‘Object’ Array Address [ ] addr = new Creating & Adding objects to an ‘Object’ Array Address [ ] addr = new](https://slidetodoc.com/presentation_image_h2/7a1e77b2e6f92eeab85aaca0328e982f/image-12.jpg)

![When an array is passed: What will print from this code segment? int [] When an array is passed: What will print from this code segment? int []](https://slidetodoc.com/presentation_image_h2/7a1e77b2e6f92eeab85aaca0328e982f/image-14.jpg)




![Interchanging adjacent elements int temp; temp = abc[i]; abc[i] = abc[i + 1]; abc Interchanging adjacent elements int temp; temp = abc[i]; abc[i] = abc[i + 1]; abc](https://slidetodoc.com/presentation_image_h2/7a1e77b2e6f92eeab85aaca0328e982f/image-19.jpg)














- Slides: 33

Topics Covered: Arrays, 1 -D & 2 -D Passing & Returning Arrays Enhanced for loop Swap/Copy Elements List Interface Array. List Class Margaret Winans, 2014 AP TIP 1

Arrays n Arrays may be declared and defined on one line (…the easy way) double[] day = new double[365]; constructor data type identifier specifies an array… an operator number of “elements” ~or~ double day [] = new double[365]; Margaret Winans, 2014 AP TIP 2

What is an Array n n A block of consecutive memory locations of the same data type. Allows many “values” to be saved in a single data structure Individual locations are called the array’s element, index, or subscript. When we say array’s “element” or “index” we mean the value stored in that element. Margaret Winans, 2014 AP TIP 3

Array Examples 5 5 INDEX = 0 to (length - 1) Margaret Winans, 2014 AP TIP 4

Indices n We can use an int variable or any expression that evaluates to an int value as an index: Examples: a [3] a [k – 2] for (int i = 0; i < array. length; i++) { System. out. print(“Name: “); array[ i ] = reader. next. Line(); } Margaret Winans, 2014 AP TIP 5

Indices (cont’d) n In Java, an array is declared with a fixed length that cannot be changed. n Java interpreter checks the values of indices at run time and throws Index. Out. Of. Bounds. Exception if an index is negative or if it is greater than the length of the array - 1. Margaret Winans, 2014 AP TIP 6

Arrays are Objects n In Java, an array is an object. n As with other objects, the declaration creates only a reference, initially set to null. n Two ways to create an array: arr. Name = new any. Type [ length ] ; or Square brackets, not parentheses! arr. Name = new any. Type [ ] { val 1, val 2, …, val. N }; Initializer List Margaret Winans, 2014 AP TIP 7

Array Objects n Because arrays are objects, all rules that apply to objects apply to arrays. n Two array variables may refer to same array. n Arrays may be garbage collected. n Array variables may be set to null. ref Margaret Winans, 2014 AP TIP ref 8

Declaring and Initializing n n n When created, space is allocated to hold array elements Unless specific values are given in an {…} list, all the elements are initialized to a default value: 0 for numbers, false for booleans, and null for objects If its elements are objects, the array holds references to objects, which are initially set to null Margaret Winans, 2014 AP TIP 9

Array Length The length of an array is determined when the array is created. n The length is either given explicitly or comes from the length of the {…} initialization list. n The length of an array arr. Name is referred to in the code as arr. Name. length. n length appears like a public field (not a method) in an array object. n Margaret Winans, 2014 AP TIP 10

Arrays that are not “full” n n Physical size: The maximum number of elements that an array can contain Logical size: The actual number of elements stored in an array n Declare an integer counter that will always indicate the number of elements. n Every time an element is added or removed, adjust the counter accordingly. n The counter indicates the logical size of the array and the next open position in the array. Margaret Winans, 2014 AP TIP 11
![Creating Adding objects to an Object Array Address addr new Creating & Adding objects to an ‘Object’ Array Address [ ] addr = new](https://slidetodoc.com/presentation_image_h2/7a1e77b2e6f92eeab85aaca0328e982f/image-12.jpg)
Creating & Adding objects to an ‘Object’ Array Address [ ] addr = new Address [20]; int ctr = 0; addr[ctr] = new Address ctr ++; (nm, str, cit, st. Zip); Margaret Winans, 2014 AP TIP 12

Passing Arrays n n n An array reference is passed to a method by using only the name of the array The array’s name contains the reference to the array & the length variable containing the size of the array (#of elements) The parameter in the called method is declared as an array of the same data type int num[ ] = new int[500]; load. Array(num); //method call public void load. Array(int numbers[]){ statements; } Margaret Winans, 2014 AP TIP numbers IS num, not a copy 13
![When an array is passed What will print from this code segment int When an array is passed: What will print from this code segment? int []](https://slidetodoc.com/presentation_image_h2/7a1e77b2e6f92eeab85aaca0328e982f/image-14.jpg)
When an array is passed: What will print from this code segment? int [] arr = {1, 2, 3, 4}; do. Something(arr); System. out. print (arr[1] + “, “ + arr[3]); public void do. Something (int [] list){ int [] b = list; for (int i = 0; i < b. length; i++) b[i] = i; } output = 1, 3 The array memory location was passed, so all changes to array ‘b’ are actually changes to the original array ‘arr’ the array now stores {0, 1, 2, 3}; Margaret Winans, 2014 AP TIP 14

Returning Arrays from Methods n n As with other objects, an array can be returned from a method. The returned array is usually constructed within the method or obtained from calls to other methods. The return type of a method that returns an array with some. Type elements is designated as some. Type [ ]. Example: public String[ ] get. Array( ) Margaret Winans, 2014 AP TIP 15

Enhanced for Loop From the first index to the last n Frees programmer from having to manage and use loop counters n aka “for-each” loop int [ ] abc = { 2, 3, 4}; int sum = 0; n for (int element : abc) sum += element; Margaret Winans, 2014 AP TIP 16

Enhanced for Loop (cont. ) n Cannot be used to: n Move through an array in reverse, from the last position to the 1 st position n Assign elements to positions in an array n Track the index position of the current element in an array n Access any element other than the current element on each pass Margaret Winans, 2014 AP TIP 17

Parallel Arrays Two or more arrays of the same size that store complementary data n Example: one array stores first names and a second stores corresponding ages. n Margaret Winans, 2014 AP TIP 18
![Interchanging adjacent elements int temp temp abci abci abci 1 abc Interchanging adjacent elements int temp; temp = abc[i]; abc[i] = abc[i + 1]; abc](https://slidetodoc.com/presentation_image_h2/7a1e77b2e6f92eeab85aaca0328e982f/image-19.jpg)
Interchanging adjacent elements int temp; temp = abc[i]; abc[i] = abc[i + 1]; abc [i + 1] = temp; Interchange Code BEFORE AFTER abc [0] = 10 temp = abc [0]; temp = 10 abc [0] = 15 abc [1] = 15 abc [0] = abc [1]; abc [0] = 15 abc [1] = 10 abc [2] = 20 abc [1] = temp; abc [1] = 10 abc [2] = 20 Margaret Winans, 2014 AP TIP 19

Copying an Array n Method to make a copy of an array and return it: private int [ ] original = {1, 2, 3, 4, 5}; private int [ ] copy; //How to call the method to create a copy = copy. Array (original); //method to copy the "original" array into a //new array named “temp“ public int[ ] copy. Array (int [ ] orig){ int [ ] temp = new int [orig. length]; for (int i = 0; i < orig. length; i++){ temp[i] = orig[i]; } return temp; } Margaret Winans, 2014 AP TIP 20

2 -Dimensional Arrays Margaret Winans, 2014 AP TIP 21

2 -D Arrays n Visualize a table with rows and columns Margaret Winans, 2014 AP TIP 22

2 -D Arrays (cont. ) n. A 2 -D array is actually an “array of arrays” n Each element of a one-dimensional array contains another array Margaret Winans, 2014 AP TIP 23

Declare/Instantiate 2 -D Array n Declaring and instantiating a two-dimensional array example: declaring: int [ ] table; instantiating: table = new int [4] [5]; // // // The variable table will reference a two-dimensional array of integers. Instantiate table as an array of size 4, each of whose elements will reference an array of 5 integers. Margaret Winans, 2014 AP TIP 24

2 -D Array Initializer List n The rows in a 2 -D array may have varying lengths. – Ragged arrays (not an AP topic ) Margaret Winans, 2014 AP TIP 25

Looping through 2 -D Array n To loop through a two-dimensional array, use nested ‘for’ loops—outer loops thru the rows & inner loops thru the columns int sum = 0; for (int i = 0; i < table. length; i++){ for (int j = 0; j < table [ i ]. length; j++) sum += table [ i ] [ j ]; ~OR~ for(int row = 0; row < table. length; row++) for(int colm = 0; colm < table[row]. length; colm++) sum += table[row][colm]; Margaret Winans, 2014 AP TIP 26

List Interface n Array. List class implements the List Interface import java. util. List; n Lists are generic n <E>is a the object type—tells compiler to check for that element type when a collection is used (java 5. 0)—Elements are declared to be of a specific object type when a list or collection variable is declared. List<E> list = new Array. List<E>(); List<String> list = new Array. List<String>(); Margaret Winans, 2014 AP TIP 27

List<Integer> list = new Array. List<Integer>(); n n The variable list is declared to be of type List<Integer> (the interface) but is instantiated as type Array. List<Integer> (the implementation)—preferred by. APCS This has the advantage of making the code applicable to any List. For example, a single change: List<Integer> list = new Linked. List<Integer>(); n The AP Quick Reference Guide (given to you for the AP exam) only gives methods of the List interface Margaret Winans, 2014 AP TIP 28

The Array. List Class n n Contains a sequence of elements ordered by position Unlike an array in that: • It uses methods rather than [] to manipulate elements. • It tracks both logical and physical size. • The logical size is 0 when created & automatically adjusts as needed. • The positions available for access range from 0 to the logical size minus 1. • Array. List can be printed without a loop Margaret Winans, 2014 AP TIP 29

AP Quick Reference Guide: List Interface n n The List interface methods below are all inherited by the Array. List This is the actual screen shot from the QRG Margaret Winans, 2014 AP TIP 30

The Array. List Class E = obj type not length boolean add(obj) Appends obj to end of the list; returns true Margaret Winans, 2014 AP TIP 31

The Array. List Class (cont. ) n n Array. List objects cannot directly store primitive types and must use wrapper classes n Boolean, Integer, Double, Character n Each wrapper class contains the value of it’s primitive type. Array. List objects automatically “box” and “unbox” primitive values when used with Array. List methods. Margaret Winans, 2014 AP TIP 32

Adding/Changing values using an Array. List //create a list of Integer objects List<Integer> list = new Array. List<Integer>(); //add int values 1 -100 to the list for (int i = 1; i <= 100; i++) list. add(i); // Increment each int in the list for (int i = 0; i < 100; i++) list. set(i, list. get(i) + 1); Margaret Winans, 2014 AP TIP 33