 Download Download Presentation Chapter 5 Arrays and Vectors

# Chapter 5 Arrays and Vectors

Télécharger la présentation ## Chapter 5 Arrays and Vectors

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
##### Presentation Transcript

1. 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.

2. 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: scores

3. 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.

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

5. 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

6. 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

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

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

9. Indexed variable • When access array elements you start at index 0 rather than 1. • salary 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……..

10. 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

11. 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

12. 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

13. Example code int[] example = new int; 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]); }

14. See code page 281 - 282 • Calculates the cubes of numbers 1-10

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

16. 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];

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

18. Case Study Pages 283 - 289 • Problem • Analysis • Design • Implementation

19. 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

20. 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

21. Given that you have 2 arrays • private int[] x = new int; • private int[] y = new int;

22. 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)

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

24. Why? X X X X x X

25. Why? X X X X x X y = x; y Old array y

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

27. 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

28. 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

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

30. 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)

31. 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; }

32. 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…..

33. 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

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

35. 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/animator/Animator.html

36. 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; }

37. 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 • Allocates storage for 5 references to an employee object, you must initialize it.

38. 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.

39. 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

40. 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!"); }

41. 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

42. 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??

43. 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?

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

45. 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.

46. 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

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

48. 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

49. 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.

50. 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]