1 / 39

Arrays

Arrays. An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values within the array, an array index is used to refer to a specific position in the array.

weylin
Download Presentation

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. Arrays • An array is a collection of data values, all of which have the same type. • The size of the array is fixed at creation. • To refer to specific values within the array, an array index is used to refer to a specific position in the array. • In Java, for an array of length n, the values in the array are indexed from 0 up to n – 1. • Notation: a refers to the entire collection a[i] refers to the value at index i

  2. Arrays A length: 6 4 7 3 -2 14 6 0 1 2 3 4 5 • A has length 6 • A[4] is 14 • If i is 3, then A[i] is -2 • Assign a value: A[5] = 6;

  3. Arrays in Java • An array variable is declared with the type of the members. • For instance, the following is a declaration of a variable of an array with members of the type double: double[] anArray; • When an array variable is declared, the array is NOT created. What we have is only a name of an array. • anArray will have the special value null until it is created.

  4. Creating an array • To create the array, operator new is used. • We must provide the number of members in the array, and the type of the members. These cannot be changed later. double[] anArray; anArray = new double[5]; or, combining the declaration and the array creation: double[] anArray = new double[5]; • When an array is created, the number of positions available in the array can be accessed using a field called length with the dot operator. For instance, anArray.length has a value 5.

  5. Array creation double[] anArray ; null anArray: Here, the array is not defined. anArray = new double[3] anArray: 0 1 2 Here, the array is defined, but the elements in the array are NOT defined. ? ? ? 3 length

  6. Accessing array members • Array members are accessed by indices using the subscript operator []. The indices are integers starting from 0. • For instance, if anArray is an array of three integers, then: • the first member is anArray[0] • the second member is anArray[1], • and the third member is anArray[2]. • The indices can be any expression that has an integer value. • If an index is out of range, i.e., less than 0 or greater than length-1, a run-time error occurs.

  7. Initializing array members • Array members can be initialized individually using the indices and the subscript operator. int [] intArray = new int[3]; intArray[0] = 3; intArray[1] = 5; intArray[2] = 4; • Array members may also be initialized when the array is created: int [] intArray; intArray = new int [] { 3, 5, 4 };

  8. Partial initialization of an Array • An array may be partially initialized. int [] intArray = new int [5]; intArray[0] = 3; intArray[1] = 5; intArray[2] = 4; • In this case, intArray[3] and intArray[4] are undefined. • When an array is processed, we may need another variable (or variables) to keep track of the indices for which we have assigned values.

  9. Reference Types • An array type is a reference type, because of the “pointer” to the array. • It is important to distinguish the reference (pointer) from the “item being pointed to”. • In the diagram below, A is the reference, and the array is what is being pointed to. • Java does not allow us to peek inside Ato see what is in the pointer. A 0 1 2 A 5 2 17 3 length

  10. 0 0 0 3 3 3 2 2 2 length length length Reference Types • What happens with assignment and comparison of reference types? • It is the references that are compared or assigned, not the arrays. A == Bis false A == Bis true A A B B

  11. 0 0 0 3 3 3 2 2 2 length length length Reference Types • Assignment only copies a reference, not the object to which is points. • How can we make a copy of an array? B = A results in: NOT: A A B B

  12. Lost references • With reference types, be careful that you don’t “lose” the item to which a reference points. • After the assignment, there is no reference to the second array. The second array will be forgotten by Java and cannot be recovered. AFTER B = A BEFORE B = A 0 3 0 3 2 2 length length A A 19 19 5 6 5 6 3 3 B B length length

  13. Example: Find maximum, minimum array values

  14. Example: Find maximum, minimum array values • Strategy: • Use variables max and min to store our current known maximum and minimum values • Start with array position 0, and assume that this value is both the maximum and minimum. • Go through each of the remaining array positions, and do the following: • Check if the value at the current array position is larger than the current maximum. • If so, replace the current maximum with the value at the current array position • Check if the value at the current array position is larger than the current minimum. • If so, replace the current minimum with the value at the current array position

  15. Example: Find position of maximum and minimum in an array • A modification of the previous problem is to find the location of the maximum and minimum values • As we loop through the array, we need to save both the maximum (and minimum) values AND their positions

  16. Methods • A method is a separate piece of code that can be called independently and/or repeatedly. • Used to partition programs into smaller portions, each of which performs a well-defined function. • We’ve already been using methods from the Math, Keyboard. • Now, we will create our own methods

  17. Method calls • When one method calls another: • The method that is currently executing stops and waits at the point of the call. • Values may be “passed” to the called method. • The called method executes. • When the called method finishes, a value may be passed back to the calling method. • The calling method restarts and continues // Statement 1 // Call method A // Statement 3 // Method A // Statement A1 // Statement A2 // return 3.5 1 6 2 3 7 4 5 6.2

  18. Components of Methods • Each method will have (optional except where noted): • name (required): used to identify method • parameters: values that must be supplied to method by caller • return value: one value returned by the method • local variables: variables used inside the method, and not accessible outside the method • body (required): code that performs the desired function

  19. Example • Horizontal motion under constant velocity • Values that must be supplied to method: • x0 (initial position), v0 (initial velocity), t (time) • Value the method must return to caller: • x (position of object at time t)

  20. Method headers • Here is the distance method: public static double findDistance( double x0, double v0, double t) { double x; // a local variable x = x0 + v0 * t; return x; // the value of x is returned to the caller } • Here is a call to the distance method: double aDistance; aDistance = findDistance( 3.0, 4.0, 7.0 ); System.out.println("The distance is " + aDistance ); • After this call, aDistance would have the value 31.0

  21. Method headers public static double findDistance( double x0, double v0, double t) • Header information • public: Accessibility: method can be called from any location in program • static: to be explained later • double: type of return value • findDistance: name of method • double x0, double v0, double t: ordered list of parameters, and their types:

  22. A method with return type void • If a method does not return a value, the return type should be void. • A call activates the method to do whatever it is supposed to do. public static void print3(int x, int y, int z) { System.out.println("This method does not return any value."); System.out.println(x); System.out.println(y); System.out.println(z); } • When the method is called by print3(3, 5, 7); it simply prints these arguments to the screen.

  23. Variables in methods • Parameter variables: • Declared in method header • Value from calling method is copied into parameter variable as method is called. • Variables are usable within the method only. • Local variables • Declared within method body • Need to be explicitly initialized • Usable within the method only. • When a method has completed, both parameter and local variables lose their values.

  24. Variable duration and scope • Duration: the “lifetime” of a variable. • Variables exist from when they are declared until the method in which they are declared has finished execution. • For the main method, this is as long as your program is running. • For other methods, this is the remainder of ONE execution of the method • If the method is called again, previous variable values would be forgotten • Scope: the parts of a program from which a variable can be accessed. • General rule: variables can be ONLY be accessed inside program block { } in which the variables are declared • Parameters: can only be accessed inside their method body.

  25. Scope class Scope { public static void method1( int x ) { int y = 1; ... } public static void method2( ) { int y = 2; int x = 3; ... for ( ... ) { int x = 4; ... } ... } } x y = 1 y = 2 x = 3 x = 4

  26. Passing of values to/from methods • When a call is made… • Execution of the calling method is suspended. • Memory is allocated for parameters and local variables of primitive types (int, double, char, boolean) in the called method. • Initial values for parameters of primitive types are COPIED from the corresponding arguments of the call. • Parameters of reference types are associated to the arrays or objects that the corresponding arguments refer to. • Execution of method body begins. • When the method body finishes, the return value is COPIED back to the calling method and the calling method resumes execution. All other values in the called method are forgotten.

  27. Arrays as Parameters • An array is a reference type. • When an array is passed from one method to another method, it is the reference that is passed to the method, not the array. • The result is that there are (temporarily) two references to the same array. • While we cannot modify the reference, we can modify the contents of the array. These changes to the array contents will remain after the method returns. • The copy of a variable of a primitive type is trashed when the method returns. • For an array, it is the copy of the reference that is trashed on return.

  28. Passing primitive and reference typesto a method At caller: m(anInt,anArray): anArray anInt 4 5 3 2 3 length copy copy At called method: m(int x, int[] y) 4 x y

  29. Parameter passing • The parameter values that are passed will remain unaffected by calling another method. • However, if you pass a reference variable, the object to which the reference points CAN be modified internally. • It is the reference that cannot be changed.

  30. Program Organization (1) • A class can contain a set of methods, in addition to main: public class VelocityMethod { public static void main(String[] args) { // Main method body } public static double findDistance( double x0, double v0, double t ) { // findDistance() method body } }

  31. Program Organization (2) • If one method is calling another method in the same class, then you only need the method name. aDistance = findDistance( 3.0, 4.0, 7.0 ); • If one method is calling another method in a different class, you will need to add the class name: aDistance = VelocityMethod.findDistance( 3.0, 4.0, 7.0 ); • To set this up, one of four conditions must be met: • The class must be one of the classes pre-loaded by Java (e.g. Math, System, …) • The class is in the software development kit, and an import statement is used (e.g. DecimalFormat) • The .class file for the called class is in the same folder on your computer (e.g. Keyboard) • The “classpath” is set in Dr. Java, where the classpath contains a list of folders to search for .class files.

  32. Example: Statistics • Create a class called Statistics with methods for • reading an array of doubles • squaring a value • finding the mean of an array • finding the standard deviation • a main method that calls the above methods to read an array and print the mean and standard deviation of all the values.

  33. Overall class structure class Statistics { public static void main (String[] args) { } public static double[] readDoubleArray( ) { } public static double standardDeviation( double[] x ) { } public static double mean( double[] x ) { } public static double xSquared( double x ) { } }

  34. Method to read array values public static double[] readDoubleArray( ) { double[] theArray; // Array of values entered by user int arraySize; // Size of 'theArray' int index; // Current array position System.out.println( "Enter an array of values."); System.out.println( ); System.out.println( "How many values in the array?" ); arraySize = Keyboard.readInt(); theArray = new double[arraySize]; for ( index = 0; index < arraySize; index++ ) { System.out.println( "Enter value at position " + index + ":" ); theArray[index] = Keyboard.readDouble(); } // Return result return theArray; }

  35. Method to square a value // This method finds the square of a value of type double. public static double xSquared( double x ) { return x * x; }

  36. Method to find arithmetic mean // This method finds the arithmetic mean of the values in array 'x'. public static double mean( double[] x ) { // Declare variables double result; // The calculated average. double sum; // Running total of array values. int index; // Array position while calculating sums. // Find sum of array elements. sum = 0.0; for ( index = 0; index < x.length; index++ ) { sum = sum + x[index]; } // Divide sum by number of elements in array. result = sum / x.length; return result; }

  37. Method to find standard deviation // This method finds the standard deviation of the values in array 'x'. public static double standardDeviation( double[] x ) { double average; // The average of the array values. double sum; // Running total of squares of differences from average double result; int index; // Array position while calculating sums. // Find average using method average = mean( x ); // Now, calculate sum of squares of differences from the mean sum = 0.0; for ( index = 0; index < x.length; index++ ) { sum = sum + xSquared( x[index] - average ); } // Final standard deviation calculation result = Math.sqrt( sum / ( x.length - 1 ) ); return result; }

  38. Main method public static void main (String[] args) { // Declare variables double[] x; // Array of values for which to find statistics double average; // Average of all values in x. double stDev; // Standard deviation of all values in x DecimalFormat df; // Used to format output // Set up decimal formatter df = new DecimalFormat("#0.00"); // Read array x = readDoubleArray( ); // Find and print mean average = mean( x ); System.out.println( "The arithmetic mean is " + df.format( average ) ); // Find and print standard deviation stDev = standardDeviation( x ); System.out.println( "The standard deviation is " + df.format( stDev ) ); }

  39. Usage as a “library” class • The class Statistics represents a useful library of methods that can be used in other classes: class AClass { double mean; double standardDev; double[] x; x = Statistics.readDoubleArray( ); mean = Statistics.mean( x ); standardDev = Statistics.standardDeviation( x ); }

More Related