1 / 45

Arrays

Arrays. Arrays. A variable can hold exactly one value An array allows us to group a number of variables, of the same type, under a single name Why use arrays? They make it easier to access “like” data and perform calculations on that data.

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

  2. Arrays • A variable can hold exactly one value • An array allows us to group a number of variables, of the same type, under a single name • Why use arrays? • They make it easier to access “like” data and perform calculations on that data. • Each location in the array is identified by its position, or index, in the array • Array indices start at 0 and run to one less than the number of locations in the array CS1 - Arrays

  3. Arrays • Arrays are data structures that hold data of the same type in contiguous memory. • A group of memory cells that are contiguous, have the same name, and store the same data type. • Each item in the array is called an array element. • Elements are accessed using the array name and an integer subscript in square brackets. • arrayName[9]; CS1 - Arrays

  4. Arrays • Arrays hold a fixed number of elements once they are created until the array is destroyed. • The size must be specified when the array is created. • ClassName [ ] arrayName = new ClassName [9]; • An element is accessed by it’s position in the array. • The first element is always arrayName[0] and the last element is always arrayName[size - 1] where size is the number of elements. arrayName[5] arrayName 0 1 2 3 4 5 8 . . . CS1 - Arrays

  5. Arrays • Arrays are objects but there is no class that array objects are instances of • This means that arrays variables are reference types • Like any reference type, before using an array you must do two things • Declare the variable that will be used to refer to the array • Create the array and assign the reference to the array to the corresponding array variable CS1 - Arrays

  6. Arrays Example: int [] arrayOfInts; Or int arrayOfInts[]; • Variables of array type are declared using bracket ([ ]) notation: typename[] varname; or typenamevarname[]; CS1 - Arrays

  7. Examples Array creation Number of locations in the array (indices will run from 0 to 9) int[] anArray; int anotherArray[]; anArray = new int[ 10 ]; int x = 15; anotherArray = new int[ x ] float [] oneLastArray = new float[ 50 ]; Array locations are initialized according to the standard initialization rules CS1 - Arrays

  8. State-of-Memory Diagram anArray x 0 1 int[] anArray; anArray = new int[ 10 ]; int [] x; x = anArray; 2 3 4 5 6 7 8 9 Can you draw a state-of-memory diagram here? CS1 - Arrays

  9. length • An array object has a public instance constant, length, that gives the number of locations in the array int anArray[] = new int[ 10 ]; system.Out.println( anArray.length ); • Once created, the length of an array is fixed !!! CS1 - Arrays

  10. Arrays double arrayOfNumbers[] = new double[13]; 0 1 2 3 4 5 6 7 8 9 10 11 12 4.5 4.2 9.9 8.2 4.5 0.0 0.1 4.5 5.2 0.3 2.0 1.3 7.8 arrayOfNumbers.length; CS1 - Arrays

  11. Declaring and Allocating Arrays • The first step is to create a reference to the array. • The reference is used to point to the object that contains the array in memory. • When a reference is created the pointer is null because the object has not been instantiated. double arrayName[]; CS1 - Arrays

  12. Declaring and Allocating Arrays • The next step is to instantiatethe array. • Instantiating the array means that the size and memory locations to hold the elements are allocated for use. double arrayName[]; arrayName = new double[10]; CS1 - Arrays

  13. Declaring and Allocating Arrays • When arrays are allocated, the elements are automatically initialized to: • zero if the array type is int, float, or double. • false if the array type is boolean. • null if the array type is String, char or an object data type. double arrayName[]; arrayName = new double[10]; CS1 - Arrays

  14. Declaring and Allocating Arrays (primitive types) // declare and initialize (implicitly) double arrayOfNumbers[ ] = new double[13]; // declare double arrayOfNumbers[ ]; // initialize (implicitly) arrayOfNumbers = new double[13]; // declare and initialize (explicitly) double[ ] arrayOfNumbers = {1.2, 3.4, 5.3, 2.1, 3.4, 2.4}; CS1 - Arrays

  15. Declaring and Allocating Arrays (reference types) • Point arrayOfPoints[ ] = new Point[15]; • Point arrayOfPoints[ ]; • arrayOfPoints = new Point[15]; CS1 - Arrays

  16. Arrays (2D) • Multi-dimension arrays can be declared by repeating pairs of brackets up to the required dimension. • The length instance variable holds the size or length of the array: • String[] words = new String[100]; • System.out.println( words.length ); // gives 100 • int [][] twoD = new int[10][20]; • System.out.println( twoD.length ); // gives 10 • System.out.println( twoD[0].length ); // gives 20 CS1 - Arrays

  17. Working with Array Values • Any array element can be used in a program like any other variable. • Must specifically reference the element in the array rather than the array name. • Can read and write to array elements as you do variables. • Can not use the entire array as you would a variable (e.g. function argument). • Example - AccessingArrays. CS1 - Arrays

  18. Working with Array Values public class arrayTest { public static void main( String args[] ) { int [] aoi = new int[5]; aoi[3] = 13; for ( int i=0; i<aoi.length; i++) System.out.print( aoi[i] + ", "); } } C:\My Documents\Misicv\RIT cs1\JavaTest>java arrayTest 0, 0, 0, 13, 0, CS1 - Arrays

  19. Initializing Arrays • We said that when an array is instantiated that it is automatically initialized to a particular value. • Integers to zero, etc. • What if you want to initialize the array to specific values? CS1 - Arrays

  20. Array Initialization • It is possible to directly initialize the values of the array elements using an initializer list: • What if you want to assign the values of the array to be the result of a specific calculation? int[] n = { 1, 2, 3, 4, 5 }; int [][] m = { {1, 2, 3, 4}, {4, 5, 6, 7}}; int [][] w = { {1, 2, 3}, {4, 5}}; CS1 - Arrays

  21. CmdLineEcho // Echo the contents of the command line public class CmdLineEcho { public static void main( String args[] ) { System.out.println("Argument list:"); System.out.println("--------------"); for (int i=0; i<args.length; i++) System.out.println( args[i] ); } } C:\My Documents\Misicv\RIT cs1\JavaTest>java CmdLineEcho –c CS1 231 Argument list: -------------- -c CS1 231 CS1 - Arrays

  22. Out-of-Bounds • Out-of-Bounds exception does not specifically refer to throwing the ball off the court or kicking a ball across the sidelines, but it is a similar concept. • Out-of-bounds occurs if a program tries to access an element of an array that is less than zero or greater than the (array.length - 1). arrayName 0 1 2 3 4 5 8 . . . CS1 - Arrays

  23. Out-of-Bounds • An exception is generated when your program accesses an element not in the array. This exception is called ArrayIndexOutOfBoundsException. • When the exception occurs, it prints out an error message and the line on which the exception occurred. • Example - OutOfBounds CS1 - Arrays

  24. Out-of-Bounds public class ArrayTest { public static void main( String args[] ) { int [] aoi = new int[5]; aoi[3] = 13; for ( int i=0; i<aoi.length+1; i++) System.out.print( aoi[i] + ", "); } } C:\My Documents\Misicv\RIT cs1\JavaTest>java ArrayTest 0, 0, 0, 13, 0, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at ArrayTest.main(ArrayTest.java:8) CS1 - Arrays

  25. Final Variables • Choosing a size for your array must be done at the time the array is instantiated. • You may not always know how many elements you will have in your array. • If the array is too small, not all the elements will fit. • If the array is too large, then there may be many elements which are not used. • The size of your array affects the speed of your program. The larger the array the slower your program runs. CS1 - Arrays

  26. Final Variables • If your program has many arrays of the same size and you need to change that size, you have to search through the program looking for all the arrays. • This may take days or weeks. • Final variables allow you to make such a change in a matter of minutes. How? CS1 - Arrays

  27. Final Variables final int MAX_SIZE = 50; ... int [] myArray = new int[MAX_SIZE]; ... ... double [] anotherArray = new double[MAX_SIZE]; ... ... ... MyClass [] lookAtThisArray = new MyClass[MAX_SIZE]; ... CS1 - Arrays

  28. Finding Things in an Array • When you are looking for a specific value in an array it is called Searching. • How many times is the number 2 in the following list? • 2, 3, 2, 6, 5, 4, 2, 2, 3, 2, 7, 2 CS1 - Arrays

  29. Searching Arrays • The easiest method of searching an array is to look at each element in an array. • This is can take a long time if the array is large but it is easy!! public class ArrayTest { public static void main( String args[] ) { int [] aoi = {2, 3, 2, 6, 5, 4, 2, 2, 3, 2, 7, 2}; ... } } Finish this program – homework !!! Can you write such program? CS1 - Arrays

  30. Passing Variables to Methods • When you pass an variable to a method via the parameter list, Java uses the pass-by-value/call-by-value method. • A copy of the value of the variable is made and passed to the method. • This means that the original variable can not be accidentally modified. • This type of method passing is used for all primitive data types: int, double, char, long • This type of method passing is used for passing an array element if it is a primitive data type. • However, array is not a primitive type!!! CS1 - Arrays

  31. Passing Objects to Methods • If your program passes an object (other than String), an array of any data type or an array element that has an object data type (other than String), the contents of the object may be changed in the method. • This will be reflected in the object referred to by the argument (actual parameter) • Have to be carefully not to accidentally change the original argument. CS1 - Arrays

  32. Passing Arrays to Methods • If you are passing an array element to a method then the method parameter is the data type of the array element. • In program: … int integerArray = new int[5]; … double res = foo( integerArray[3] ); … • In function declaration: … double foo(int x) { … } CS1 - Arrays

  33. Passing Arrays to Methods int numbers[] = {5, 6, 34, 45}; Point points[] = new Point[4]; intMethod(numbers[1]); pointMethod(points[2]); intArrayMethod(numbers); pointArrayMethod(points); public void intMethod (int number) { number += 4; } public void pointMethod (Point point) { point.setXLocation(6); } public void intArrayMethod(int[ ] numbersArray) { numbersArray[3] = 10; } public void pointArrayMethod(Point[ ] pointArray) { pointArray[0].setXLocation(89); } CS1 - Arrays

  34. Multi-dimensional Arrays • Multi-dimensional Arrays (or multiple-subscripted arrays) can be used to represent tables of data. • A 2-dimensional array has rows and columns and two subscripts are needed to access the array elements. • We may have n rows and m columns which means we have an n-by-m array. CS1 - Arrays

  35. Multi-dimensional Arrays • Java represents multi-dimensional arrays using a single dimensional array whose individual elements are a single dimensional array. • Given this definition we can create arrays that are 2D, 3D, 4D, 5D, etc. • Usually the highest dimension that will be used is 3D. • Also given this definition, not all dimensions have to hold the same number of elements. CS1 - Arrays

  36. Multi-dimensional Arrays • The elements of multi-dimensional arrays are accessed similarly to single dimensional arrays. • Instead of using a single subscript, a two dimensional array uses two subscripts. arrayName[i][j] = value; CS1 - Arrays

  37. Multi-dimensional Arrays int arrayOfNums[ ][ ] = new int[3][4]; Col 0 Col 1 Col 2 Col 3 Row 0 13 23 33 43 Row 1 14 24 34 44 Row 2 15 25 35 45 CS1 - Arrays

  38. Multi-dimensional Arrays • You do not have to define a multi-dimensional array to have the same number of columns in each row. • int arrayOfNums[][]; arrayOfNums = new int[3][]; arrayOfNums[0] = new int[2]; arrayOfNums[1] = new int[3]; arrayOfNums[2] = new int[4]; CS1 - Arrays

  39. Multi-dimensional Arrays Col 0 Col 1 Col 2 Col 3 Row 0 13 23 Row 1 14 24 34 Row 2 15 25 35 45 CS1 - Arrays

  40. Multi-dimensional Arrays • Initializing values in a multi-dimensional array can be completed similarly to single dimensional arrays. int[][] arrayOfNums = {{13, 23, 33, 44}, {14, 24, 34, 44}, {15, 25, 35, 45}}; CS1 - Arrays

  41. Multi-dimensional Arrays double numbers[][] = new double[6][5]; for (int i = 0; i < numbers.length; i++) for (int j = 0; j < numbers[0].length; j++) numbers[i][j] = 10*(i+1) + (j+1); CS1 - Arrays

  42. Scope • Scope: area of “visibility” of some variable (either primitive or complex). • Variable exist only within the method in which is defined. • In the method: variable exists only in the code-block in which it is defined. I am confused: what about complex variables??? CS1 - Arrays

  43. Scope 1 class Scope { // Class Variables: private static int numberOfScopes = 0; // Instance Variables: public int a; public int b; // Class methods: public static int getNumberOfScopes() { return numberOfScopes; } // Constructors: public Scope( ) { a = 1; b = 2; numberOfScopes++; } // Methods : public int method1( int param1, int param2 ) { int a = 5; int b = 10; int c; c = param1*a + param2*b; param1 = 100; return c; } } public static void main( String args[] ) { int a = 10; int b = 20; int c; Scope s = new Scope(); c = s.method1( a, b ); } Originally: a, b = 10, 20 s.a, s.b = 1, 2 After method1: a, b, c = 10, 20, 250 s.a, s.b = 1, 2 CS1 - Arrays

  44. Scope 2 class Scope { // Class Variables: private static int numberOfScopes = 0; // Instance Variables: public int a; public int b; // Class methods: public static int getNumberOfScopes() { return numberOfScopes; } // Constructors: public Scope( ) { a = 1; b = 2; numberOfScopes++; } // Methods : public void method2( int param1, int param2 ) a = param1; b = param2; } } public static void main( String args[] ) { int a = 10; int b = 20; int c; Scope s = new Scope(); s.method2( a, b ); } Originally: a, b = 10, 20 s.a, s.b = 1, 2 After method2: a, b = 10, 20 s.a, s.b = 10, 20 CS1 - Arrays

  45. Scope 3 class Scope { // Class Variables: private static int numberOfScopes = 0; // Instance Variables: public int a; public int b; // Class methods: public static int getNumberOfScopes() { return numberOfScopes; } // Constructors: public Scope( ) { a = 1; b = 2; numberOfScopes++; } // Methods : public Scope method3( Scope s, int param1, int param2 ) { Scope w = new Scope (); w.method2( param1, param2 ); s.method2( 50, 100); return w; } public void method2( int param1, int param2 ) a = param1; b = param2; } } public static void main( String args[] ) { int a = 10; int b = 20; Scope s = new Scope(); Scope t; t = s.method3( s, a, b ); } Originally: a, b = 10, 20 s.a, s.b = 1, 2 After method3: a, b = 10, 20 s.a, s.b = 50, 100 t.a, t.b = 10, 20 numberOfScopes = 2 CS1 - Arrays

More Related