Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5 Arrays and Vectors An array allows you to group data items together in a structure that is processed via an index. They allow you to process.

Similar presentations


Presentation on theme: "Chapter 5 Arrays and Vectors An array allows you to group data items together in a structure that is processed via an index. They allow you to process."— Presentation transcript:

1

2 Chapter 5 Arrays and Vectors An array allows you to group data items together in a structure that is processed via an index. They allow you to process like data items as a group. Objects can also be stored in an array.

3 Array declarations and indices An array is a data structure in which we store a collection of data items of the same type. Arrays have a single variable name associated with the entire collection. Array of scores: 8895336785 scores

4 Arrays Arrays are stored in consecutive memory locations in main memory. We can pass entire arrays to methods We can access the individual array elements. We can process the individual elements like other simple variables.

5 Declaring arrays Double[] salary = new double[50]; Declares an array of type double that can hold 50 values Array type Array name Array size

6 Declaring arrays int[] coinValues = {1, 5, 10, 25, 50}; Alternative method to declare and initialize array. What is the length of the array? Array Type Array name Array Values

7 Syntax Display Form: elementType[] arrayName = new elementType[size]; elementType[] arrayName = {list-of-values}; arrayName represents a collection of array elements each element can store an item of type elementType The size maybe specified or calculated based on the number of values in the list-of-values. These items are stored sequentially. elementType can be primitive type or class

8 Declaration versus Storage allocation You can declare an array and storage separately. double[] salary; salary = new double[50]; Why would you want to do this?

9 Processing array elements An array index is used to process the individual array elements. You use the array name and an index displayResult(salary[1]); You can use this anywhere you would use a value of that type. The index is either an integer or an integer expression.

10 Indexed variable When access array elements you start at index 0 rather than 1. salary[1] is called an indexed variable. Salary is type double so we can use this anywhere we use a double, arithmetic operators, relational operators, the assignment operator……..

11 Examples Review example 5.1 on page 275 - 276 This uses literals as index Review example 5.2 on page 276 This uses variables as the index You must be assured that the variable is in the valid range of index values. Out of bounds error Occurs at runtime

12 Section 5.2 processing arrays For loops are typically used to process an array They allow you to process all elements in an array in some way Can be used to: Enter data Display contents Perform other processing

13 Data field length Java automatically allocates a data field Length Allocated for each array Stores the array size in this data field Can be used to process an array. See code example 5.3 page 279

14 Example code int[] example = new int[5]; for (int i = 0; i < example.length; i++) example[i] = getInt("please enter an integer"); for (int i = 4; i >= 0; i--) displayResult(example[i]); }

15 See code page 281 - 282 Calculates the cubes of numbers 1-10

16 Array cube example First create array but does not set length private int[] cubes; Then sets length of array via cubes = new int[numCubes];

17 Array cube example Fills the array via: for (int i = 0; i < cubes.length; i++) cubes[i] = i * i * i; Calculates the sum of cubes: for (int i = 0; i < cubes.length; i++) sumCubes += cubes[i];

18 Array cube example Displays results via for (int i = 0; i < cubes.length; i++) “glues” string together next Look at running of example code.

19 Case Study Pages 283 - 289 Problem Analysis Design Implementation

20 Operations on whole arrays 5.3 Can pass an entire array as an argument Assign values from on array to another Copy data from one array to another

21 Array copy System.arraycopy(sourceArray, sourcePosition, destinationArray, destinationPostion, count); System.arraycopy(y, 0, x, 0, y.length); Copies y to x but remain separate arrays System.arraycopy(y, 0, x, 2, 3); Copies y starting at 0 for next 3 positions to x starting at position 2

22 Given that you have 2 arrays private int[] x = new int[5]; private int[] y = new int[5];

23 Array Assignment x = y; Makes x and y occupy the same storage space! Very different than other assignment statements. They are now identical If you change elements of one it changes the other. (same storage space)

24 Why?? When you declare an array int[] x = new int[5]; This allocates 5 storage locations x[0] through x[4]; Additionally java allocates an additional storage location x which contains the address of the start of the array

25 Why? 00000 x X[0] X[1] X[3]X[2]X[4]

26 Why? 00000 x X[0] X[1] X[3]X[2]X[4] y = x; 00000 yOld array y

27 Example 5.16 Page 294 5.16 Accepts in 2 arrays Returns true is they are equal Middle of page Calls the method

28 Example 5.7 page 295 - 296 Adds 2 arrays Accepts in 2 integer arrays Returns an array which is the sum of the respective elements in the arrays sent

29 Section 5.4 Searching and Sorting an Array Two common things that are done with an array are: Searching Sorting When we search an array you compare each value to a target, which is the value you are seeking

30 PseudoCode For each array element If the current element contains the target return the index of the current element If none found return -1

31 Implementation To test each element of the array we would use a for loop. The arrays length attribute can be used for the upper limit (< length)

32 Search code public static int search(int[] x, int target) { for (int i = 0; i < x.length; i++) if (x[i] == target) return i; //index of target // All elements tested without success. return -1; }

33 Sorting array Selection sort is a simple sorting algorithm It is not a very efficient algorithm Finds smallest element in the array and switches it with element in position 0 Finds next smallest element and switches it with position 1 And so on…..

34 Pseudocode For each index, fill, in the array up to but excluding, the last index Find the smallest element in the subarray starting at scores[fill] If the smallest element is not at index fill Exchange the smallest element with the one at index fill See code trace page 300

35 Switching values If you want to change to values x, y need a third storage location temp = x; x = y; y = temp;

36 Sort program Look at sorting code on page 301 Method selectSort Method findPosMin Look at selection sort running at http://www.cs.hope.edu/~alganim/animat or/Animator.html http://www.cs.hope.edu/~alganim/animat or/Animator.html

37 Median Value Easy to find median in sorted Array Simply one in the middle public static int findMedian(int x[]) { // Create a copy of array x. int[] copyX = new int[x.length]; System.arraycopy(x, 0, copyX, 0, x.length); selectSort(copyX); // Sort array copyX if (x.length % 2 == 1) return copyX[x.length / 2]; else return (copyX[(x.length / 2) – 1] + copyX[x.length/2]) / 2; }

38 Arrays of Objects 7.5 Arrays can be declared of any type in Java. When you create an array of objects you actually have an array of null references to objects. Employee[] employees new Employee[5] Allocates storage for 5 references to an employee object, you must initialize it.

39 Examples Page 304 - 305 Example shows creating an array of references to 5 strings. Page 304 shows creating array and then setting values. Page 305 this declares the array and initializes it at the same time.

40 Array of string as argument You can pass array of strings to methods. We have been using the format all along. public static void main(String[] args); Passes command line parameters into the program as string arguments

41 Code looks like this public static void main(String[] args) { if (args.length > 0) for(int i = args.length - 1; i >=0; i--) System.out.println(args[i]); else System.out.println("No command line args - no fun!"); }

42 Case study Payroll problem Uses company class to include array of employee objects from section 4.4 New company needs to include 2 new data items Array of employees Total Gross pay

43 Case study Payroll problem pages 312 - 314 Implementation Notice readPayrollData, simply uses a for loop to instantiate the objects and call method to prompt user for data. computePayRoll uses a for loop to total the pay of all employees Could this, Should this have been a part of readAllEmpData??

44 Case study Payroll problem Implementation I have a problem with the design of this. It revolves around the data field payroll And the method computePayroll Especially being public Any ideas what I don’t like about this?

45 Case Study Phone Directory Study the Phone Directory Case study Work to understand this! Come with questions for next time.

46 Multidimensional Arrays section 5.6 How many can we have? Two dimensional are the most common arrays. These allow more complex structures than just the linear nature of single dimensional arrays.

47 Multidimensional Arrays The rules for element types of multidimensional arrays are the same for single dimensional arrays Must be the same type Can be simple or objects Most commonly used to represent a table of elements

48 Declaring 2 dimensional arrays char [] [] ticTacToe = new char[3][3]; This is a 2d array with 3 rows and 3 columns. ticTacToe [1] [2] Array name Row index Column index

49 Initializing a two-dimensional array double [] [] matrix = {{5.0, 4.5, 3.0}, {-16.0, -5.9, 0.0}}; Creates an 2 X 3 array Col 0Col 1Col 2 Row 05.04.53.0 Row 1-16.0-5.90.0

50 Nested loops for processing 2d arrays. You need to decide what order you intend on accessing the array. If in row order, then the row index in used in the outer loop. If in column order then the column index is in the outer loop.

51 Nested loops for processing 2d arrays. Pseudocode: for each row r in the array for each column c in the array process the element with indices [r] [c]

52 Code to process int intArray [] [] = new int [3] [3]; for (int row = 0; row < intArray.length, row++) for (int col = 0; col < intArray[row].length, col++) process each array element intArray[row] [col]

53 Arrays with different row lengths Since each row of a 2d array is it’s own 1d array the length of all row need not be equal

54 Arrays > 2d Why? Each row is a player and each column is how many hits they had in each game. 2d array represents a team with each column a different player 3d represents all the teams in the league 4d represents various seasons for the league

55 Section 7.7 Vectors Vectors are a class within java. They allow for much of the flexibility that you will learn to implement in CS2 Must import java.util.*; Only works with objects not primitive types

56 Vector attributes Allows structure to grow and shrink as needed Allows you to: Add elements Retrieve elements Insert elements Remove elements

57 Example 5.14 Page 329 Uses vector to store a collection of employees Vector employees = new Vector(); employees.addElement(employeeA); employees.addElement(employeeB); Puts employeeA at index 0 Puts employeeB at index 1

58 Accessing elements anEmployee = (Employee)employees.elementAt(1); Assigns to an Employee the second element in array elementAt returns a type object so you must type cast it to the appropriate type (Employee)

59 Other methods setElementAt Allows you to change an element in the vector insertElementAt Allows you to insert an element anywhere in the vector removeElementAt Allows you to delete any element in the vector See table 5.3 page 332

60 Review re-do of phone book On pages 334 – 336 is a re-do of the Phone Book app you looked at before. Study and compare this to the previous example and come prepare to ask any questions next time

61 Wrapper classes Section 5.8 Vectors can only work on objects not primitive data types A Wrapper class encapsulates a primitive type and allows it to function as an object. Contains methods for converting back and forth.

62 Wrapper class methods Constructor takes primitive type and create object of that type class new Double(3.14159) Holds real number 3.14159 in type Double object

63 Wrapper class methods Constructor to decode string into objects initial value Double w = new Double(“3.14159”); Stores 3.14159 in object of type Double that is called w

64 Wrapper class methods toString method creates string version w.toString() creates “3.14159” typeValue gives primitive type value w.DoubleValue() gives 3.14159 equals compares objects of same type x.equals(y) is true if the wrap the same value

65 Vectors and Wrappers You need to know what vectors are Characteristics Capabilities Uses You need to know what Wrapper classes are Capabilities Uses

66 Section 5.9 Arrays and ArrayList collection classes Arrays class provides a set of static methods to process arrays fill() sort() binarySearch() equals() We will write our own for some of these

67 ArrayList Provides and indexed collection behave like a vector has greater performance See methods page 343 See Phone book re-write using ArrayList Pages 343 - 346

68 Common programming errors Most common error is index going outside the bounds of the array May want to display index to be sure that it is processing properly. Index type must be integer Must declare array and create an instance or it. If not get null pointer error

69 Common programming errors Vectors Do not remove more data than is in the vector Be sure to type cast objects as you remove them To store primitives in vector must use wrapper class


Download ppt "Chapter 5 Arrays and Vectors An array allows you to group data items together in a structure that is processed via an index. They allow you to process."

Similar presentations


Ads by Google