Presentation is loading. Please wait.

Presentation is loading. Please wait.

Topics Covered: Arrays, 1-D & 2-D Passing & Returning Arrays

Similar presentations


Presentation on theme: "Topics Covered: Arrays, 1-D & 2-D Passing & Returning Arrays"— Presentation transcript:

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

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

3 What is an Array 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. There is indeed some confusion in the usage of “element.” In some situations, the word refers to the location in an array, as in “set the value of the k-th element.” In other situations it refers to a value stored in the array, as in “find the smallest element.” This dual usage is somewhat similar to the situation with the term “variable.” This is no big deal, as long as everyone understands the difference between a location and a value stored in it. Margaret Winans, 2014 AP TIP

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

5 Indices We can use an int variable or any expression that evaluates to an int value as an index: That’s the beauty of it: the index may be a variable calculated at run time; it can be used in algorithms. Examples: a [3] a [k] a [k – 2] for (int i = 0; i < array.length; i++) { System.out.print(“Name: “); array[ i ] = reader.nextLine(); } Margaret Winans, 2014 AP TIP

6 Indices (cont’d) In Java, an array is declared with a fixed length that cannot be changed. Java interpreter checks the values of indices at run time and throws IndexOutOfBoundsException if an index is negative or if it is greater than the length of the array - 1. arr = new int[newSize]; does not really resize arr: it simply throws away the old array and allocates a new one with default values. “Throws an exception” means reports a run-time error with rather detailed information about where in the code it occurred and aborts the program. Margaret Winans, 2014 AP TIP

7 Square brackets, not parentheses!
Arrays are Objects In Java, an array is an object. As with other objects, the declaration creates only a reference, initially set to null. Two ways to create an array: The second form, with a list of initial values, is not in the AP subset. arrName = new anyType [ length ] ; Square brackets, not parentheses! or arrName = new anyType [ ] { val1, val2, …, valN }; Initializer List Margaret Winans, 2014 AP TIP

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

9 Declaring and Initializing
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 As for fields: 0 for numbers, false for booleans, null for objects. The elements get default values even if an array is a local variable. You can think of an array’s elements as sort of like its “fields.” Margaret Winans, 2014 AP TIP

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

11 Arrays that are not “full”
Physical size: The maximum number of elements that an array can contain Logical size: The actual number of elements stored in an array Declare an integer counter that will always indicate the number of elements. Every time an element is added or removed, adjust the counter accordingly. The counter indicates the logical size of the array and the next open position in the array. Margaret Winans, 2014 AP TIP

12 Creating & Adding objects to an ‘Object’ Array
Address [ ] addr = new Address [20]; int ctr = 0; addr[ctr] = new Address (nm, str, cit, stZip); ctr ++; Margaret Winans, 2014 AP TIP

13 Passing Arrays 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]; loadArray(num); //method call public void loadArray(int numbers[]){ statements; } numbers IS num, not a copy Margaret Winans, 2014 AP TIP

14 When an array is passed:
What will print from this code segment? int [] arr = {1, 2, 3, 4}; doSomething(arr); System.out.print (arr[1] + “, “ + arr[3]); public void doSomething (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

15 Returning Arrays from Methods
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 someType elements is designated as someType [ ]. Example: public String[ ] getArray( ) It is helpful to think of someType[ ] as a data type designation, “array of someType elements.” Margaret Winans, 2014 AP TIP

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

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

18 Parallel Arrays Two or more arrays of the same size that store complementary data Example: one array stores first names and a second stores corresponding ages. Margaret Winans, 2014 AP TIP

19 Interchanging adjacent elements
int temp; temp = abc[i]; abc[i] = abc[i + 1]; abc [i + 1] = temp; BEFORE abc [0] = 10 abc [1] = 15 abc [2] = 20 Interchange Code temp = abc [0]; temp = 10 abc [0] = abc [1]; abc [0] = 15 abc [1] = temp; abc [1] = 10 AFTER abc [0] = 15 abc [1] = 10 abc [2] = 20 Margaret Winans, 2014 AP TIP

20 Copying an Array 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 = copyArray (original); //method to copy the "original" array into a //new array named “temp“ public int[ ] copyArray (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

21 2-Dimensional Arrays Margaret Winans, 2014 AP TIP

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

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

24 Declare/Instantiate 2-D Array
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

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

26 Looping through 2-D Array
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

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

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

29 The ArrayList Class 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. ArrayList can be printed without a loop Margaret Winans, 2014 AP TIP

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

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

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

33 Adding/Changing values using an ArrayList
//create a list of Integer objects List<Integer> list = new ArrayList<Integer>(); //add int values 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


Download ppt "Topics Covered: Arrays, 1-D & 2-D Passing & Returning Arrays"

Similar presentations


Ads by Google