1 / 125

Chapter 7 Arrays

Chapter 7 Arrays. Arrays are objects that help us organize large amounts of information Data structures Related data items of same type Remain same size once created Fixed-length entries Think –Lists. Introducing Arrays.

rstamper
Télécharger la présentation

Chapter 7 Arrays

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 Arrays are objects that help us organize large amounts of information • Data structures • Related data items of same type • Remain same size once created • Fixed-length entries Think –Lists

  2. Introducing Arrays Array is a data structure that represents a collection of the same types of data.

  3. The values held in an array are called array elements • An array stores multiple values of the same type – the element type • The element type can be a primitive type or an object reference • Therefore, we can create an array of integers, an array of characters, an array of String objects, an array of Coin objects, etc. • In Java, the array itself is an object that must be instantiated

  4. Declaring Array Variables • datatype[] arrayRefVar; Example: double[] myList; • datatypearrayRefVar[]; // This style is allowed, but not preferred Example: double myList[];

  5. Declaring Arrays double[ ] measurements = new double[24]; char[ ] ratings = new char[100]; int[ ] points = new int[4]; • String [] names= new String[100]; • String [] colors = {“red”, “green”, “blue”}; float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750]; See Github examples Week8

  6. Creating Arrays arrayRefVar = new datatype[arraySize]; Example: myList = new double[10]; myList[0] references the first element in the array. myList[9] references the last element in the array.

  7. Declaring and Creatingin One Step • datatype[] arrayRefVar = new datatype[arraySize]; double[] myList = new double[10];

  8. For example, an array element can be assigned a value, printed, or used in a calculation scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1])/2; System.out.println ("Top = " + scores[5]);

  9. The Length of an Array Once an array is created, its size is fixed. It cannot be changed. You can find its size using arrayRefVar.length For example, myList.length returns 10

  10. Default Values When an array is created, its elements are assigned the default value of 0 for the numeric primitive data types, '\u0000' for char types, and false for boolean types.

  11. Array Initializers • Declaring, creating, initializing in one step: double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand syntax must be in one statement.

  12. Declaring, creating, initializing Using the Shorthand Notation double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand notation is equivalent to the following statements: double[] myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5;

  13. CAUTION Using the shorthand notation, you have to declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error. For example, the following is wrong: double[] myList; myList = {1.9, 2.9, 3.4, 3.5};

  14. Initializer Lists • Note that when an initializer list is used • the new operator is not used • no size value is specified • The size of the array is determined by the number of items in the initializer list • An initializer list can be used only in the array declaration

  15. Arrays as Parameters • An entire array can be passed as a parameter to a method • Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other • Therefore, changing an array element within the method changes the original • An individual array element can be passed to a method as well, in which case the type of the formal parameter is the same as the element type

  16. Arrays of Objects • The elements of an array can be object references • The following declaration reserves space to store 5 references to String objects String[] words = new String[5]; • It does not create the String objects themselves • Initially an array of objects holds null references • Each object stored in an array must be instantiated separately

  17. - words - - - - 7.3 – Arrays of Objects • The words array when initially declared • At this point, the following reference would throw a NullPointerException System.out.println (words[0]);

  18. “friendship” words “loyalty” “honor” - - Arrays of Objects • After some String objects are created and stored in the array

  19. animation Trace Program with Arrays Declare array variable values, create an array, and assign its reference to values public class Test { public static void main(String[] args) { int[] values = new int[5]; for (inti = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } }

  20. animation Trace Program with Arrays i becomes 1 public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } }

  21. animation Trace Program with Arrays i (=1) is less than 5 public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } }

  22. animation Trace Program with Arrays After this line is executed, value[1] is 1 public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } }

  23. animation Trace Program with Arrays After i++, i becomes 2 public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } }

  24. animation Trace Program with Arrays i (= 2) is less than 5 public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } }

  25. animation Trace Program with Arrays After this line is executed, values[2] is 3 (2 + 1) public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } }

  26. animation Trace Program with Arrays After this, i becomes 3. public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } }

  27. animation Trace Program with Arrays i (=3) is still less than 5. public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } }

  28. animation Trace Program with Arrays After this line, values[3] becomes 6 (3 + 3) public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } }

  29. animation Trace Program with Arrays After this, i becomes 4 public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } }

  30. animation Trace Program with Arrays i (=4) is still less than 5 public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } }

  31. animation Trace Program with Arrays After this, values[4] becomes 10 (4 + 6) public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } }

  32. animation Trace Program with Arrays After i++, i becomes 5 public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } }

  33. animation Trace Program with Arrays i ( =5) < 5 is false. Exit the loop public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } }

  34. animation ArrayDefaultValue Trace Program with Arrays After this line, values[0] is 11 (1 + 10) public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } Example on Github Week8- ArrayDefaultValue.java

  35. Iterators and Complete Array processing • The iterator version of the for loop can be used when processing array elements for (int score : scores) System.out.println (score); • This is only appropriate when processing all array elements from top (lowest index) to bottom (highest index)

  36. public class BasicArray { //----------------------------------------------------------------- // Creates an array, fills it with various integer values, // modifies one value, then prints them out. //----------------------------------------------------------------- public static void main (String[] args) { final int LIMIT = 15, MULTIPLE = 10; int[] list = new int[LIMIT]; // Initialize the array values for (int index = 0; index < LIMIT; index++) list[index] = index * MULTIPLE; list[5] = 999; // change one array value // Print the array values for (int value : list) System.out.print (value + " "); } }

  37. Bounds Checking !!!!! • Once an array is created, it has a fixed size • An index used in an array reference must specify a valid element • That is, the index value must be in range 0 to N-1 • The Java interpreter throws an ArrayIndexOutOfBoundsExceptionif an array index is out of bounds • This is called automatic bounds checking Example on Github Week8- OutofBound.java

  38. Bounds Checking • Each array object has a public constant called length that stores the size of the array • It is referenced using the array name scores.length • Note that length holds the number of elements, not the largest index

  39. problem • For example, if the array codes can hold 100 values, it can be indexed using only the numbers 0 to 99 • If the value of count is 100, then the following reference will cause an exception to be thrown System.out.println (codes[count]); • It’s common to introduce off-by-one errors when using arrays for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon;

  40. Variable Length Parameter Lists • Suppose we wanted to create a method that processed a different amount of data from one invocation to the next • For example, let's define a method called average that returns the average of a set of integer parameters // one call to average three values mean1 = average (42, 69, 37); // another call to average seven values mean2 = average (35, 43, 93, 23, 40, 21, 75);

  41. We could define overloaded versions of the average method • Downside: we'd need a separate version of the method for each parameter count • We could define the method to accept an array of integers • Downside: we'd have to create the array and store the integers prior to calling the method each time • Instead, Java provides a convenient way to create variable length parameter lists

  42. Indicates a variable length parameter list element type array name Variable Length Parameter Lists • Using special syntax in the formal parameter list, we can define a method to accept any number of parameters of the same type • For each call, the parameters are automatically put into an array for easy processing in the method public double average (int ... list) { // whatever }

  43. Variable Length Parameter Lists public double average (int ... list) { double result = 0.0; if (list.length != 0) { int sum = 0; for (int num : list) sum += num; result = (double)num / list.length; } return result; }

  44. Variable Length Parameter Lists • The type of the parameter can be any primitive or object type public void printGrades (Grade ... grades) { for (Grade letterGrade : grades) System.out.println (letterGrade); }

  45. Variable Length Parameter Lists • A method that accepts a variable number of parameters can also accept other parameters • The following method accepts an int, a String object, and a variable number of double values into an array called nums public void test (int count, String name, double ... nums) { // whatever }

  46. Read one hundred numbers, compute their average, and find out how many numbers are above the average. Solution AnalyzeNumbers Run with prepared input

  47. The Arrays.sort Method Since sorting is frequently used in programming, Java provides several overloaded sort methods for sorting an array of int, double, char, short, long, and float in the java.util.Arrays class. For example, the following code sorts an array of numbers and an array of characters. double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5}; java.util.Arrays.sort(numbers); char[] chars = {'a', 'A', '4', 'F', 'D', 'P'}; java.util.Arrays.sort(chars);

  48. Initializing arrays with input values java.util.Scanner input = new java.util.Scanner(System.in); System.out.print("Enter " + myList.length + " values: "); for (int i = 0; i < myList.length; i++) myList[i] = input.nextDouble();

  49. Initializing arrays with random values for (int i = 0; i < myList.length; i++) { myList[i] = Math.random() * 100; }

  50. Printing arrays for (int i = 0; i < myList.length; i++) { System.out.print(myList[i] + " "); }

More Related