Presentation is loading. Please wait.

Presentation is loading. Please wait.

Objects First with Java CITS1001

Similar presentations


Presentation on theme: "Objects First with Java CITS1001"— Presentation transcript:

1 Objects First with Java CITS1001
Arrays CITS1001 © David J. Barnes and Michael Kölling

2 Scope of this lecture Arrays (fixed size collections)
Declaring and constructing arrays Using and returning arrays Aliasing Reading: Chapter 7 of Objects First with Java 6th Edition Chapter 5 in the 5th and earlier Editions

3 Fixed-size collections
Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Fixed-size collections Sometimes the maximum collection size can be pre-determined. A special fixed-size collection type is available: an array. Unlike the flexible List collections, arrays can store object references or primitive-type values. Arrays use a special syntax. © David J. Barnes and Michael Kölling

4 The weblog-analyzer project
Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling The weblog-analyzer project Web server records details of each access. Supports analysis tasks: Most popular pages. Busiest periods. How much data is being delivered. Broken references. Analyze accesses by hour. © David J. Barnes and Michael Kölling

5 Creating an array object
Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Creating an array object Array variable declaration — does not contain size public class LogAnalyzer { private int[] hourCounts; private LogfileReader reader; public LogAnalyzer() hourCounts = new int[24]; reader = new LogfileReader(); } ... Array object creation — specifies size © David J. Barnes and Michael Kölling

6 Objects First with Java
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling The hourCounts array © David J. Barnes and Michael Kölling

7 Objects First with Java
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Using an array Square-bracket notation is used to access an array element: hourCounts[...] Elements are used like ordinary variables. The target of an assignment: hourCounts[hour] = ...; In an expression: hourCounts[hour]++; adjusted = hourCounts[hour] – 3; © David J. Barnes and Michael Kölling

8 Objects First with Java
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Standard array use private int[] hourCounts; private String[] names; ... hourCounts = new int[24]; hourcounts[i] = 0; hourcounts[i]++; System.out.println(hourcounts[i]); declaration creation use © David J. Barnes and Michael Kölling

9 Objects First with Java
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Practice Write a declaration for an array variable vacant that could be used to refer to an array of boolean variables. Write a declaration for an array variable lettercounts that could be used to refer to an array that counts the frequency of letters of the alphabet. Now write a statement to create this array. What is wrong with the following declarations? Correct them. []int counts; boolean[5000] occupied; © David J. Barnes and Michael Kölling

10 Objects First with Java
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Array literals The size is inferred from the data. private int[] numbers = { 3, 15, 4, 5 }; declaration, creation and initialization Array literals in this form can only be used in declarations. Related uses require new: numbers = new int[] { , 15, 4, 5 }; © David J. Barnes and Michael Kölling

11 Objects First with Java
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Array length private int[] numbers = { 3, 15, 4, 5 }; int n = numbers.length; no brackets! NB: length is a field rather than a method! It cannot be changed – ‘fixed size’. © David J. Barnes and Michael Kölling

12 The for loop (reminder)
Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling The for loop (reminder) There are two variations of the for loop, for-each and for. The for loop is often used to iterate a fixed number of times. Often used with a variable that changes a fixed amount on each iteration. © David J. Barnes and Michael Kölling

13 Objects First with Java
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling For loop pseudo-code General form of the for loop for(initialization; condition; post-body action) { statements to be repeated } Equivalent in while-loop form initialization; while(condition) { statements to be repeated post-body action } © David J. Barnes and Michael Kölling

14 Objects First with Java
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling A Java example for loop version for(int hour = 0; hour < hourCounts.length; hour++) { System.out.println(hour + ": " + hourCounts[hour]); } while loop version int hour = 0; while(hour < hourCounts.length) { System.out.println(hour + ": " + hourCounts[hour]); hour++; } © David J. Barnes and Michael Kölling

15 Objects First with Java
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Practice Fill an array with the Fibonacci sequence. int[] fib = new int[100]; fib[0] = 0; fib[1] = 1; for ... © David J. Barnes and Michael Kölling

16 for loop with bigger step
Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling for loop with bigger step // Print multiples of 3 that are below 40. for(int num = 3; num < 40; num = num + 3) { System.out.println(num); } © David J. Barnes and Michael Kölling

17 Practice How many String objects are created by the following declaration? String[] labels = new String[20]; What is wrong with the following array creation? Correct it. double[] prices = new double(50);

18 Practice Correct all the errors in the following method. /**
Print all values in the marks array that are greater than mean. @param marks An array of mark values. @param mean The mean (average) mark. */ public void printGreater(double marks, double mean) { for (index = 0; index <= marks.length(); index++) { if (marks[index] > mean) { System.out.println(marks[index]); }

19 Challenge A Lab Class has a limit to the number of students who may be enrolled in a particular tutorial group. In view of this, would it be more appropriate to use an fixed-size (eg array) or flexible (eg ArrayList) collection for the students in a particular lab? Give reasons both for and against the alternatives.

20 Objects First with Java
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Review Arrays are appropriate where a fixed-size collection is required. Arrays use a special syntax. For loops are used when an index variable is required. For loops offer an alternative to while loops when the number of repetitions is known. Used with a regular step size. © David J. Barnes and Michael Kölling

21 Objects First with Java More examples
Using ARRAYS More examples © David J. Barnes and Michael Kölling

22 Uses of arrays Arrays are used when we have large numbers of identical objects that we want to operate on as a collection A collection of student marks that we want to analyse A collection of temperatures that we want to average A collection of names that we want to sort e.g. Bureau of Meteorology data ALBANY Max Min Rain PERTH AIRPORT Max Min Rain

23 Declaring arrays An array is declared using similar syntax to any other variable int[] a; Declares a to be a variable representing an array of ints double[] temps; Declares temps to be a variable representing an array of doubles String[] names; Declares names to be a variable representing an array of Strings Student[] marks; Declares marks to be a variable representing an array of Student objects

24 Creating Arrays I An array is an object in a Java program
Therefore the declaration simply creates a reference to “point to” the array, but does not create the array itself Hence the declaration int[] a; creates a space called a, big enough to hold an object reference, and initially set to the special value null Only space for the array reference has been created, not for the array itself a null

25 Creating Arrays II In order to actually create the array, we must use the keyword new (just like creating any other object) int[] a; a = new int[7]; An object is created that contains seven variables of type int a The expression a.length can be used to refer to the size of a

26 Creating Arrays III The seven variables do not have individual names
They are referred to by the array name, and an index a[0] a[1] a[2] a[3] a[4] a[5] a[6] a

27 Referencing array elements
Array elements can be used in the same ways and in the same contexts as any other variable of that type a[4] = 15; a[2] = 7; a[3] = 2*a[2] – a[4]; a[6] = a[0] + 17; a[0] a[1] a[2] 7 a[3] -1 a[4] 15 a[5] a[6] 17

28 Indexing arrays A lot of the power of arrays comes from the fact that the index can be a variable or an expression int x = 3; a[x] = 5; a[7-x] = 44; a[0] a[1] a[2] 7 a[3] 5 a[4] 44 a[5] a[6] 17

29 Summing the integers in an array
private int sum(int[] a) { int sum=0; for (int ai : a) { sum = sum + ai; } return sum; Here ai is an element of the array a The for-each loop is the best choice for this problem because we are accessing every element of the array and not removing or adding any elements

30 Or using a for loop private int sum(int[] a) { int sum = 0;
Here i is being used as an index into the array a private int sum(int[] a) { int sum = 0; for (int i = 0; i < a.length; i++) sum = sum + a[i]; } return sum;

31 Find the biggest integer in an array
Note that this is only well-defined for non-empty arrays! Again i is an element of the array a private int max(int[] a) { int max = a[0]; for (int i : a) if (i > max) max = i; } return max;

32 Or using a for loop private int max(int[] a) { int max = a[0];
Here i is being used as an index into the array a private int max(int[] a) { int max = a[0]; for (int i = 1; i < a.length; i++) if (a[i] > max) max = a[i]; } return max;

33 Find the index of the biggest integer
private int max(int[] a) { int k = 0; for (int i = 1; i < a.length; i++) { if (a[i] > a[k]) { k = i; } return k; A for-each loop will not work for this example. Why not?

34 Returning an array Suppose we want to find the running sums of a
private int[] sums(int[] a) { int[] sums = new int[a.length]; sums[0] = a[0]; for (int i = 1; i < a.length; i++) sums[i] = sums[i–1] + a[i]; } return sums;

35 Returning an array Suppose we want to average each pair of elements of a avs({2,6,–8,2}) = {4,–3} private int[] avs(int[] a) { int[] avs = new int[a.length / 2]; for (int i = 0; i < a.length-1; i = i+2) avs[i / 2] = (a[i] + a[i+1]) / 2; } return avs;

36 Updating an array Sometimes instead of creating a new array, we want to update the old one But this method doesn’t return anything… private void sums(int[] a) { for (int i = 1; i < a.length; i++) a[i] = a[i–1] + a[i]; }

37 Arrays can share memory
int[] a, b; a b

38 Arrays can share memory
int[] a, b; a = new int[3]; a b

39 Arrays can share memory
int[] a, b; a = new int[3]; b = a; a b

40 Arrays can share memory
int[] a, b; a = new int[3]; b = a; System.out.println(b[2]); a b

41 Arrays can share memory
int[] a, b; a = new int[3]; b = a; System.out.println(b[2]); a[2] = 9; 9 a b

42 Arrays can share memory
int[] a, b; a = new int[3]; b = a; System.out.println(b[2]); a[2] = 9; 9 9 a b

43 Aliasing This is called aliasing Basically one array with two names
It applies in the same way with any other object-types too Be careful with equality over arrays In some applications we might want to use aliasing deliberately

44 Changes to parameters are usually lost
When we call a method with a parameter of a primitive type, any updates to the parameter are local only The parameter is a new variable private void f(int a) {a = 666;} int x = 5; System.out.println(x); f(x); 5 x is unchanged

45 But arrays are persistent
When we call a method with a parameter of object type, the parameter is a new variable but it refers to the same space on the heap private void f(int[] a) {a[0] = 666;} int[] x = {5,3,1}; System.out.println(x[0]); f(x); 5 666 x is unchanged but x[0] is changed

46 Objects First with Java
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Review Arrays are appropriate where a fixed-size collection is required. Arrays and for-loops go together Methods can return arrays Arrays are reference types: if you pass an array as a parameter and change it within a method, then the change will be visible afterwards. © David J. Barnes and Michael Kölling

47 Objects First with Java CITS1001
MORE Arrays CITS1001 © David J. Barnes and Michael Kölling

48 Scope of this lecture Arrays of objects Multi-dimensional arrays
The Game of Life (next lecture)

49 Objects First with Java
Arrays of objects The arrays we have seen so far had elements of a primitive type int[], double[], boolean[], etc. But an array can also hold objects e.g. Term[] Arrays can also be two-dimensional e.g. int[][] Arrays can also be three-dimensional, or more But we won’t get to that in CITS1001 © David J. Barnes and Michael Kölling

50 Objects First with Java
Arrays of objects When using an array of primitive type, there are two steps involved Declare the variable to refer to the array Create the space for the array elements using new When using an array of object type, there are three steps involved Populate the array with objects by repeatedly using new, often in a loop © David J. Barnes and Michael Kölling

51 A Student class public class Student { private String studentNumber; private int mark; public Student(String studentNumber, int mark) { this.studentNumber = studentNumber; this.mark = mark; } public String getStudentNumber() { return studentNumber; public int getMark() { return mark; A skeleton version of a possible Student class in a student records system

52 Creating a unit list Declare Create Populate Student[] unitList;
unitList = new Student[numStudents]; unitList[0] = new Student(“042371X”,64); unitList[1] = new Student(“ ”,72); unitList[2] = new Student(“ ”,55); unitList[numStudents-1] = new Student(“ ”,85); Declare Create Populate

53 The three steps unit null unit null null null null null unit[0]

54 Using arrays of objects
Using an array of objects is the same as using any array You just need to remember that the elements are objects! private Student top(Student[] unitlist) { Student top = unitlist[0]; for (Student si : unitlist) if (si.getMark() > top.getMark()) top = si; return top; }

55 Compare with max private int max(int[] a) { int max = a[0];
for (int i : a) if (i > max) max = i; return max; }

56 Student top(Student[] unitList)
Method signatures int max(int[] a) Student top(Student[] unitList)

57 Initialisation int max = a[0]; Declare a variable to hold the “best so far”, and initialise it to the first element in the array Student top = unitList[0];

58 Processing for (int i : a) if (i > max) max = i; Check each element in turn, compare it with the best so far, and update the best if necessary for (Student si : unitList) if (si.getMark() > top.getMark()) top = si;

59 Return return max; Finally return the extreme element – the highest int or the Student with the best mark return top;

60 What if we want to find the highest mark?
private int highestMark(Student[] unitlist) { int max = unitlist[0].getMark(); for (Student si : unitlist) if (si.getMark() > max) max = si.getMark(); return max; }

61 Much better to use the existing method!
Do not write another looping method! Use the already-written functionality private int highestMark(Student[] unitlist) { return top(unitlist).getMark(); }

62 Objects First with Java
2D arrays We sometimes need arrays with more than one dimension int[][] a = new int[4][3]; a[0][0] a[0][1] a[0][2] This creates an array with four “rows” and three “columns” The “row” index ranges from 0–3 and the “column” index from 0–2 a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2] a[3][0] a[3][1] a[3][2] © David J. Barnes and Michael Kölling

63 2D arrays contd. This is really an array where each element is itself an array a is a valid variable, representing the whole thing a[0] is a valid variable, representing the first “row” a[0][2] is a valid variable, representing the last element in the first “row”

64 2D arrays contd. a a[0] a[1] a[2] a[3] a[0][0] a[0][1] a[0][2] a[1][0]
a[0][1] a[0][2] a[0] a[1][0] a[1][1] a[1][2] a[1] a a[2][0] a[2][1] a[2][2] a[2] a[3][0] a[3][1] a[3][2] a[3]

65 2D arrays contd. Given that an array is an object, this is really just a special case of an array of objects The single statement int[][] a = new int[4][3]; declares the array variable a, and both creates and populates the array!

66 2D arrays examples A 2D array is normally processed with two nested for-loops private int sum(int[][] a) { int sum = 0; for (int i = 0; i < a.length; i++) for (int j = 0; j < a[i].length; j++) sum = sum + a[i][j]; return sum; }

67 2D arrays examples Suppose we want to return the index of the first row containing any element that is true private int firsttrue(boolean[][] a) { for (int i = 0; i < a.length; i++) for (int j = 0; j < a[i].length; j++) if (a[i][j]) return i; return -1; }

68 2D arrays example We will illustrate the use of 2D arrays further with a case study of The Game of Life In the next lecture… And there’s plenty of practice in the lab too


Download ppt "Objects First with Java CITS1001"

Similar presentations


Ads by Google