1 / 114

Chapter Topics

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. Chapter Topics.

underwoodl
Download Presentation

Chapter Topics

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

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

  3. Introduction to Arrays Primitive variables are designed to hold only one value at a time. e.g., int number; Arrays allow us to create a collection of like values that are indexed. An array can store any type of data but only one type of data at a time. An array is a list of data elements. e.g., int[ ] numbers; numbers

  4. Introduction to Arrays final int ARRAY_SIZE = 5; int [] numbers = new int[ARRAY_SIZE]; numbers[0] = 25; numbers[3] = 45; final int ARRAY_SIZE = 5; int [] numbers = new int[ARRAY_SIZE]; numbers[0] = 25; numbers[3] = 45; numbers variable numbers[4] numbers[3] numbers[0] numbers[1] numbers[2] Array element values are initialized to 0.

  5. Creating Arrays An array is an object so it needs an object reference. // 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 variable. // Create a new array that will hold 6 integers. numbers = new int[6]; 0 0 0 0 0 0 index 0 index 1 index 2 index 3 index 4 index 5 Array element values are initialized to 0.Array indexes always start at 0.

  6. Creating Arrays It is possible to declare an array reference and create it in the same statement.int[] numbers = new int[6]; numbers variable numbers references an array with memory for 6 int values Arrays may be of any type. Elem 0 Elem 1 ….. Elem 5 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 non-negative number. It may be a literal value, a constant, or variable. Use a final variable as a size declarator. final int ARRAY_SIZE = 6; int[] numbers = new int[ARRAY_SIZE]; Once created, an array size is fixed and cannot be changed.

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

  9. Inputting and OutputtingArray Elements Array elements can be treated as any other variable. They are simply accessed by the same name and a subscript. See example: ArrayDemo1.java Array subscripts can be accessed using variables (such as for loop counters). for (int index = 0; numbers[index] > 0 && index < 6; index++) { System.out.printf(“numbers [ %d ] is %d.”, index, numbers[index]) }; See example: ArrayDemo2.java

  10. Bounds Checking Array indexes always start at zero and continue to (array length - 1). int values = new int[10]; size = values.length;//assign 10 to the size. This array would have indexes 0 through 9. See example: InvalidSubscript.java In for loops, it is typical to use i, j, and k as counting variables. It might help to think of i as representing the word index.

  11. 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]; int[] numbers_i = new int[100]; for (int i = 1; i <= 100; i++){ numbers[i] = 99; numbers_i[i] = i;} Here, the equal sign allows the loop to continue on to index 100, where 99 is the last index in the array. This code would throw an ArrayIndexOutOfBoundsException.

  12. Array Initialization //use new keyword to create an array object int[ ] days = new int[12]; // or int [ ] days; days = new int[12]; // or final int DAYS_SIZE = 12; int [ ] days = new int[DAYS_Size]; See example: ArrayInitialization.java days

  13. Array Initialization //use new keyword to create an array object int[ ] days = new int[12]; //Or int [ ] days; days = new int[12]; Once an array is created, its size cannot be changed. By default, Java initializes array elements with 0. Java performs array bounds checking, which means that it does not allow a statement to use a subscript that is outside the range of valid subscripts for an array. The valid subscripts for the array days are 0 through 11. See example: ArrayInitialization.java days

  14. 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. days[11] is assigned 31. See example: ArrayInitialization.java

  15. Alternate Array Declaration Previously we showed arrays being declared: declare an array variable numbers which does not create an array. int[] numbers; However, the brackets can also go here: int numbers[]; These are equivalent but the first style is typical. Then use the new key word to create an array and assigned it address to the numbers variable. numbers = new int[6]; Or we simply write int [ ] numbers = {101, 102, 103, 104, 105};

  16. 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 typical. Multiple arrays can be declared on the same line. int[] numbers, codes, scores; With the alternate notation each variable must have brackets. int numbers[], codes[], scores; The scores variable in this instance is simply an int variable.

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

  18. Processing Array Contents Processing data in an array is the same as any other variable. grossPay = hours[3] * payRate; Pre and post increment works the same for the content of array score[i]: int[] score = {7, 8, 3, 10, 11}; ++score[2]; // Pre-increment operation score[4]++; // Post-increment operation See example: PayArray.java System.out.println(++score[2] + “ ” + score[2]); System.out.println(score[4]++ + “ ” + score[4]);

  19. The Enhanced for Loop Simplified array processing (read only) Always goes through all elements General format: for(datatypeelementVariable : array) statement;

  20. The Enhanced for Loop Example: //create an object array with the variable numbers as // reference to int[] numbers = {3, 6, 9}; for(int val : numbers) { System.out.println("The next value is " + val); }

  21. The Enhanced for Loop Example: int[] numbers = {3, 6, 9}; for(int val : numbers) { System.out.println("The next value is " + val); } Output; The next value is 3 The next value is 6 The next value is 9

  22. Array Length Arrays are objects and provide a public field named lengththat is a constant that can be tested. 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. Cannot change the value of an array’s length field.

  23. 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 one less than the array length.

  24. Array Size You can let the user specify the size of an array: int numTests; int[] tests; Scanner keyboard = new Scanner(System.in); System.out.print("How many tests do you have?"); numTests = keyboard.nextInt(); tests = new int[numTests]; See example: DisplayTestScores.java

  25. import java.util.Scanner; publicclass arrayLecture07 { publicstaticvoid main(String[] args) { intnumTests; int[] tests; Scanner keyboard = new Scanner(System.in); System.out.print("How many tests do you have?"); numTests = keyboard.nextInt(); tests = newint[numTests]; System.out.print("tests array's length is " + tests.length + "\n"); for (intindex=0; index < tests.length; index++) { System.out.print(tests[index] + " "); } } } How many tests do you have?8 tests array's length is 8 0 0 0 0 0 0 0 0

  26. 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]; If the first (10 element) array no longer has a reference to it, it will be garbage collected. numbers

  27. 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]; int []numbersc = numbers; //a reference copy // Reassign numbers to a new array. numbers = new int[5]; If the first (10 element) array no longer has a reference to it, it will be garbage collected. numbersc numbers

  28. import java.util.Scanner; publicclass arrayLecture07 { publicstaticvoid main(String[] args) { intnumTests; double [] tests; Scanner keyboard = new Scanner(System.in); System.out.print("How many tests do you have?"); numTests = keyboard.nextInt(); tests = newdouble[numTests]; System.out.print("tests array's length is " + tests.length + "\n"); for (intindex=0; index < tests.length; index++) { System.out.print("Enter the " + index + " score:"); tests[index] = keyboard.nextDouble(); } for (intindex=0; index < tests.length; index++) { System.out.print(tests[index] + " "); } //continue to the next slide

  29. tests = newdouble[5]; System.out.print("\ntests array's length is " + tests.length + "\n"); for (intindex=0; index < tests.length; index++) { System.out.print("Enter the " + index + " score:"); tests[index] = keyboard.nextDouble(); } for (intindex=0; index < tests.length; index++) { System.out.print(tests[index] + " "); } } //end of main } How many tests do you have?3 tests array's length is 3 Enter the 0 score:100 Enter the 1 score:101 Enter the 2 score:99 100.0 101.0 99.0 tests array's length is 5 Enter the 0 score:95.01 Enter the 1 score:95.02 Enter the 2 score:95.03 Enter the 3 score:95.04 Enter the 4 score:95.05 95.01 95.02 95.03 95.04 95.05 test Before the end of execution of the second for loop.

  30. Reassigning Array References The numbers variable holds the address of an int array. Address int[] numbers = new int[10];

  31. Reassigning Array References int[] numbers = new int[10]; This array gets marked for garbage collection The numbers variable holds the address of an int array. Address numbers = new int[5];

  32. Copying Arrays This is not the way to copy an array. int[] array1 = { 2, 4, 6, 8, 10 }; int[] array2 = array1; // This does not copy array1. 2 4 6 8 10 array1 holds an address to the array Address Example:SameArray.java array2 holds an address to the array Address

  33. Copying Arrays This is not the way to copy an array. int[] array1 = { 2, 4, 6, 8, 10 }; int[] array2 = array1; // This does not copy array1. int [ ] array1 = new int[5]; Or int [ ] array1; array1 = new int[5]; // This statement is to set array2 to reference the same array. 2 4 6 8 10 array1 array1 holds an address to the array Address This type of assignment operation is called a reference copy. Namely, only the address of the array object is copied, not the contents of the array object. array2 holds an address to the array Address array2 Example: SameArray.java

  34. Copying Arrays You cannot copy an array by merely assigning one reference variable to another. You need to copy the individual elements of one array to another. 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 firstArray to the corresponding element of secondArray.

  35. Copying Arrays You cannot copy an array by merely assigning one reference variable to another. You need to copy the individual elements of one array to another. 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 firstArray to the corresponding element of secondArray. firstArray address secondArray address

  36. 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: PassElements.java More often you will want to write methods to process array data by passing the entire array, not just one element at a time.

  37. Passing Arrays as Arguments Arrays are objects. Their references can be passed to methods like any other object reference variable. 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] + " "); } Example: PassArray.java

  38. 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. public class PassElements{ public static void main(String[ ] args){ int [] nos = {5, 10, 15, 20, 25}; for(int i = 0; i < nos.length; i++) { displayElement(nos[i]); } //end for } //end main public static void displayElement(int content){ System.out.print(content + “, ”);}//end displayElement }content The program output is 5, 10, 15, 20, 25, nos address nos[4] 25

  39. 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. int [] nos = {5, 10, 15, 20, 25}; int i = 0; displayElement(nos[i], nos[i+1], nos[i+2], nos[i+3], nos[i+4]); // displayElement(nos[0], nos[1], nos[2], nos[3], nos[4]); public static void displayElement(int c0, int c1, int c2, intc3, int c4){ System.out.print(c0 + “, ” + c1 + “, ” + c2 + “, ”+ c3 + “, ” + c4 + “, ” );}//end displayElement. An awkward way! The program output is 5, 10, 15, 20, 25, nos address nos[1] nos[0] c0 5 10 c1

  40. public class PassElements{ public static void main(String[ ] args){ int [] nos = {5, 10, 15, 20, 25}; int i = 0; displayElement(nos[i], nos[i+1], nos[i+2], nos[i+3], nos[i+4]); // displayElement(nos[0], nos[1], nos[2], nos[3], nos[4]); } //end main public static void displayElement(int c0, int c1, int c2, intc3, int c4){ System.out.print(c0 + “, ” + c1 + “, ” + c2 + “, ”+ c3 + “, ” + c4 + “, ” ); }//end displayElement. An awkward way! } The output is: 5, 10, 15, 20, 25

  41. Passing Array as Arguments to a Method More often you will want to write methods to process array data by passing the entire array, not just one element at a time. When pass an array as an argument, it simply pass the value in the variable that reference the array, as shown below public static void main(String[ ] args){ int [] numbers = {5, 10, 15, 20, 25, 30, 35, 40}; showArray(numbers); … } public static vod showArray(int[] array) { … } .. number address A reference copy! address array

  42. Passing Arrays as Arguments Arrays are objects. Their references can be passed to methods like any other object reference variable. 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] + " "); } Example: PassArray.java

  43. public class PassArrayReferenceVariable{ public static void main(String[ ] args){ int [] numbers = {5, 10, 15, 20, 25, 30, 35, 40}; showArray(numbers); } //end main public static void showArray(int [] arrayContents) { System.out.print(arrayContents); System.out.print("\n"); for(int i = 0; i < arrayContents.length; i++) System.out.print(arrayContents[i] + " ");; } //end of showArray} } The output is: [I@15db9742 5 10 15 20 25 30 35 40

  44. Comparing Arrays The == operator determines only whether array references point to the same array object. firstArray secondArray int[] firstArray = { 5, 10, 15, 20, 25 }; int[] secondArray = { 5, 10, 15, 20, 25 }; if (firstArray == secondArray) //This is a mistake. System.out.println("The arrays are the same."); else System.out.println("The arrays are not the same."); The program output is The arrays are not the same. ……………. Why?

  45. Comparing Arrays: Example int[] firstArray = { 2, 4, 6, 8, 10 }; int[] secondArray = { 2, 4, 6, 8, 10 }; boolean arraysEqual = true; int i = 0; // First determine whether the arrays are the same size. if (firstArray.length != secondArray.length) { arraysEqual = false;} // Next determine whether the elements contain the same data. 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.");

  46. Useful Array Operations Finding the Highest Value int [] numbers = new int[50]; int highest = numbers[0]; 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]; } By default numbers[0] = 0 numbers[1] = 0 … numbers[49] = 0 highest and lowest have values which are 0.

  47. public class HighestLowestValues{ public static void main(String[ ] args){ final int ARRAY_SIZE = 15; int [] numbers01 = new int[ARRAY_SIZE ]; getValues(numbers01); int highest = numbers01[0]; for (int index = 1; index < numbers01.length; index++) { if (numbers01[index] > highest) highest = numbers01[index]; } System.out.println("\nThe highest numbers is " + highest); int lowest = numbers01[0]; for (int index = 1; index < numbers01.length; index++) { if (numbers01[index] < lowest) lowest = numbers01[index]; } System.out.println("The lowest numbers is " + lowest); }//end of main

  48. public static void getValues(int [] arrayNumbers){ Random randomNumbers = new Random(); for(int i = 0; i < arrayNumbers.length; i++){ arrayNumbers[i] = randomNumbers.nextInt(100)+1; System.out.print(arrayNumbers[i] + " "); } } }//end of class HighestLowestValues The output is: 79 77 56 3 3 96 18 18 25 98 63 93 69 30 36 The highest numbers is 98 The lowest numbers is 3

  49. 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];}//end for_loop average = total / scores.length; Example: SalesData.java, Sales.java

More Related