1 / 99

Starting Out with Java: Early Objects Third Edition

Chapter 7: Arrays and the ArrayList Class. Starting Out with Java: Early Objects Third Edition by Tony Gaddis as modified for CSCI 1250/1260. Chapter Topics. Chapter 7 discusses the following main topics: Introduction to Arrays Processing Array Contents

sonora
Download Presentation

Starting Out with Java: Early Objects Third Edition

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 7:Arrays and the ArrayList Class Starting Out with Java: Early Objects Third Edition by Tony Gaddis as modified for CSCI 1250/1260

  2. Chapter Topics Chapter 7 discusses the following main topics: • Introduction to Arrays • Processing Array Contents • Passing Arrays as Arguments to Methods • Some Useful Array Algorithms and Operations • Returning Arrays from Methods • String Arrays • Arrays of Objects

  3. Chapter Topics Chapter 7 discusses the following main topics: • The Sequential Search Algorithm • Two-Dimensional Arrays • Arrays with Three or More Dimensions • The Selection Sort and the Binary Search • Command-Line Arguments • The ArrayList Class

  4. Introduction to Arrays • Primitive variables are designed to hold only one value at a time. • Arrays allow us to create a collection of values of a singletype. • This collection is indexed so that we can access any item in the array using its index. The index of the first item is 0. • An array can store any type of data but only one type of data at a time per array – in other words, all items in the collection must be of the same type (all integers, all doubles, allStrings, etc.). • An array can be thought of as a list or table of data elements.

  5. Creating Arrays • An array is an object so it needs an object reference. Square brackets designate an array. // Declare a reference to an array that will hold integers int[] numbers; • The next step creates the array and assigns its address to the numbers reference variable // Create a new array that will hold 6 integers numbers = new int[6]; • The array may be viewed as either a row or as a column of values 0 0 0 0 0 0 index 0 index 1 index 2 index 3 index 4 index 5 Integer array element values are initialized to 0.Array indexes always start at 0. The last subscript is always the one less than the size.

  6. Creating Arrays • We may declare an array reference and create a new array instance in the same statement. int[] numbers = new int[6]; • Arrays may be of any single type. Some arrays of primitive types are shown here. float[] temperatures = new float[100]; char[] letters = new char[41]; long[] units = new long[50]; double[] sizes = new double[1200];

  7. Creating Arrays • The array size must be a positive integer • It may be a literal value, a constant, or variable final intARRAY_SIZE = 6; int[] numbers = new int[ARRAY_SIZE]; • Using a named constant is preferred because the array size may be used in many places in the code and this way provides for easy changes, if and when they are needed • Once created, an array size is fixed and cannot be changed

  8. Accessing the Elements of an Array 20 0 0 0 0 0 0 0 numbers[0] numbers[1] numbers[2] numbers[3] numbers[4] numbers[5] • An array is accessed by: • the reference name and • a subscript or index that identifies which element in the array to access numbers[0] = 20; //pronounced "numbers sub zero“ // or “numbers index zero”

  9. Inputting and Outputting Array Elements • Array elements can be used as any other variables • They are simply accessed by the arrayname and a subscript • See example on next slide: ArrayDemo1.java • Array subscripts can be variables (such as for loop counters) • See example (slide 7-11) : ArrayDemo2.java

  10. I/O with Array Elements

  11. I/O with Array Elements

  12. Bounds Checking • Array indexesalways start at zero and continue through (array length - 1) int[ ] values = new int[10]; • This array would have indexes 0 through 9 • See example (next slide): InvalidSubscript.java

  13. Bounds Checking Exception thrown and program crashes when index is 3

  14. Off-by-One Errors • It is very easy to be off-by-one when accessing arrays // This code has an off-by-one error int[] numbers = new int[100]; for (int i = 1; i<= 100; i++) numbers[i] = 99; • Whenireaches 100, this code would throw an ArrayIndexOutOfBoundsException because there is no position number 100 – the last one is position 99 Here, the equal sign allows the loop to continue to index 100, even though99 is the last index in the array

  15. Array Initialization • When relatively few items need to be initialized, an initialization list can be used to initialize the array int[]days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; • The numbers in the list are stored in the array in order: • days[0] is assigned 31 • days[1]is assigned 28 • days[2] is assigned 31 • days[3] is assigned 30 • etc. • See example (next 2 slides): ArrayInitialization.java

  16. Array Initialization

  17. Example repeated Added String array of month names Obtained both monthName and number of days from the two arrays using the same index for both

  18. Array initialization • In addition to initializing an array as shown on the previous slides, one may assign an existing array object to the new array reference • For example, if Face is an enumerated type listing all of the faces in a playing card, the following creates an array of Faces named myFaces and initializes it with all of the possible faces using the values method that is present in all enumerated types Face[ ] myFaces = Face.values( );

  19. Alternate Array Declaration • Previously we showed arrays being declared: int[ ] numbers; • However, the brackets can also go here: int numbers[ ]; • These are equivalent but the first style is more common • Multiple arrays can be declared on the same line with the original notation int[ ] numbers, codes, scores; • With the alternate notation each variable must have its own set of brackets int numbers[ ], codes[ ], scores; • The scores variable in this instance is simply an ordinary int variable

  20. Processing Array Contents • Processing a data item in an array is done in the same ways as any other variable grossPay = hours[3] * payRate; • Pre and post increment/decrement also works the same: int[] score = {7, 8, 9, 10, 11}; ++score[2]; // Pre-increment operation score[4]++; // Post-increment operation • See example (see next slide): PayArray.java

  21. Processing Array Contents

  22. Processing Array Contents • Array elements can be used in relational operations: if(cost[20] < cost[0]) { //statements } • They can be used in loopconditions: while(value[count] != 0) { //statements }

  23. The Enhanced for Loop This means we canuse values in the array with this technique, but we should not change them • Simplified array processing (read only) • Always goes through all elements. Can be thought of as “for each item in the array, do … ” • General: for(datatypeelementVariableName : arrayName) { statement; } • Example: int[] numbers = {3, 6, 9}; for(int val : numbers) { System.out.println("The next value is " + val); } Read this as “for each integer, named val, in the array named numbers” …

  24. Array Length • Arrays are objects and provide a publicfield named lengththat is a constant that can be tested, displayed, compared, etc. double[] temperatures = new double[25]; • The length of this array is 25 • The length of an array can be obtained via its length constant int size = temperatures.length; • The variable size will contain 25

  25. Array Size • The length constant can be used in a loop to provide automatic bounding for(int i = 0; i < temperatures.length; i++) { System.out.println("Temperature " + i ": " + temperatures[i]); } Index subscripts start at 0 and end at oneless than the array length.

  26. Array Size • You can let the user specify the size of an array (but you should check to make sure the user specifies a reasonable size): int numTests; int[] tests; Scanner keyboard = new Scanner(System.in); System.out.print("How many tests (1-9)? "); numTests = keyboard.nextInt( ); if (numTests > 0 && numTests < 10) tests = new int[numTests]; • See example (next slide): DisplayTestScores.java

  27. Array Size Should verify that numTests is reasonable

  28. Reassigning Array References • An array reference can be assigned to another array of the same type // Create an array referenced by the numbers variable. int[] numbers = new int[10]; // Reassign numbers to a new array. numbers = new int[5]; • After the first (10-element) array no longer has a reference to it, it will be garbage collected

  29. Reassigning Array References new array to which numbers refers numbers int[] numbers = new int[10]; The numbers variable holds the address of an intarray Address

  30. Reassigning Array References This array is marked for garbage collection since it is no longer referenced The numbers variable holds the address of an int array. Address numbers = new int[5];

  31. Copying Arrays Shallow copy vs. deep copy; this incorrect approach is called a shallowcopy • This is not the way to copy an array int[] array1 = { 2, 4, 6, 8, 10 }; int[] array2 = array1; // This does not copy array1 Shallow copy simply makes both items refer to same physical array 2 4 6 8 10 array1 holds an address to the array Address Example:SameArray.java array2 holds an address to the array Address

  32. Copying Arrays – Deep Copy • You cannot copy an array by merely assigning one reference variable to another • To copy an array, you must first have two separate arrays of the same size ( and not just two references to the same array) • Then you must copy the individual elements of onearray to the other, one at a time in a loop int[] firstArray = {5, 10, 15, 20, 25 }; int[] secondArray = new int[5]; for (int i = 0; i < firstArray.length; i++) secondArray[i] = firstArray[i]; • This code copies each element of the firstArray to the corresponding element of the secondArray Two separatearrays Called a Deep Copy

  33. Passing Array Elements to a Method • When a single element of an array is passed to a method it is handled like any other variable • See example (next slide): PassElements.java

  34. Passing a single element of an array Array element used as a parameter

  35. Passing Arrays as Arguments showArray(numbers); 5 10 15 20 25 30 35 40 Address public static void showArray(int[] array) { for (int i = 0; i < array.length; i++) System.out.print(array[i] + " "); } • Arrays are objects • Their references can be passed to methods like any other object reference variable Example: PassArray.java

  36. Comparing Arrays • The ==operator determines only whether array references refer to the same array object • To compare the contents of an array the proper way: int[] firstArray = { 2, 4, 6, 8, 10 }; int[] secondArray = { 2, 4, 6, 8, 10 }; // Assume they are equal until we have evidence they are not boolean arraysEqual = true; int i = 0; if (firstArray.length != secondArray.length) arraysEqual = false; while (arraysEqual && i < firstArray.length) { if (firstArray[i] != secondArray[i]) arraysEqual = false; i++; } if (arraysEqual) System.out.println("The arrays are equal."); else System.out.println("The arrays are not equal.");

  37. Array Algorithms • There are many algorithms for doing common things with arrays • Fill (or populate) an array • Display array • Find largest/smallest value in an array • Determine whether an array contains a particular value • Sort the data in the array into some order • Some of these algorithms are given in examples in subsequent slides

  38. Finding the largest • For small sets of values, we can almost “see” the answer without giving much thought • For larger sets of values, we need a mental “algorithm” • The computer cannot just see the answer - it needs an algorithm • We scan the items one at a time • The first is the largest we have seen when it is the only one we have seen • Scan the rest until we find a larger one • Remember it • Repeat previous two steps until finished • What we are remembering at the end is the largest

  39. Useful Array Operations • Finding the Highest Value int [] numbers = new int[50]; // Assume the array has now been filled with integers int highest = numbers[0]; // First is largest so far for (int i = 1; i < numbers.length; i++) { if (numbers[i] > highest) highest = numbers[i]; } • Finding the Lowest Value int lowest = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (numbers[i] < lowest) lowest = numbers[i]; } Starting with the second item – the one in position 1 – scan the rest, comparing each to the largest seen so far

  40. Useful Array Operations • Summing Array Elements: int total = 0; // Initialize accumulator for (int i = 0; i < units.length; i++) total += units[i]; • Averaging Array Elements: double total = 0; // Initialize accumulator double average; // Will hold the average for (int i = 0; i < scores.length; i++) total += scores[i]; average = total / scores.length; • Example (next slides): SalesData.java, Sales.java

  41. Example

  42. Example Continued

  43. Partially Filled Arrays • Typically, if the amount of data that an array must hold is unknown: • Set the size of the array to the largest number of elements you MIGHT need • Use a counting variable to keep track of how much valid data is in the array (remember the length of the array is the number of values it could hold – not the number it does hold, which could be fewer) … int[] array = new int[100]; int count = 0; … System.out.print("Enter a number or -1 to quit: "); number = keyboard.nextInt(); while (number != -1 && count <= 99) { array[count] = number; count++; System.out.print("Enter a number or -1 to quit: "); number = keyboard.nextInt(); } … Assumenumber, and keyboard were previously declared and keyboardreferences a Scanner object

  44. Returning an Array Reference

  45. String Arrays Address “Bill” names[0] address “Susan” names[1] address “Steven” names[2] address “Jean” names[3] address • Arrays are not limited to primitive data • An array of String objects can be created: String[] names = { "Bill", "Susan", "Steven", "Jean" }; The names variable holds the address to the array A Stringarray is an array of references to Stringobjects Example (next slide):MonthDays.java

  46. String Array Example

  47. String Arrays • If an initialization list is not provided, the newkeyword must be used to create the array: String[] names = new String[4]; The names variable holds the address to the array Address names[0] null names[1] null names[2] null names[3] null

  48. String Arrays names[0] = "Bill"; names[1] = "Susan"; names[2] = "Steven"; names[3] = "Jean"; “Bill” “Susan” “Steven” “Jean” • When an array is created in this manner, each element of the array must be initialized individually The names variable holds the address to the array Address names[0] names[1] names[2] names[3]

  49. Calling String Methods On Array Elements • String objects have several methods, including: • toUpperCase • compareTo • equals • charAt • Each element of a String array is a String object • Methods of the String class can be used by giving the arrayname and index as before System.out.println(names[0].toUpperCase()); char letter = names[3].charAt(0);

  50. The length Field & The length Method • Arrays have a finalfield (attribute) named length • String objects have a methodnamed length • To display the length of each string held in a String array: for (int i = 0; i < names.length; i++) System.out.println(names[i].length()); • An array’s length is an attribute (field) • You do not use a set of parentheses after its name • A String’s length is a method • You do place the parentheses after the name of the String class’s length method

More Related