Presentation is loading. Please wait.

Presentation is loading. Please wait.

Unit 5 1 Arrays and Vectors H Arrays and vectors are objects that help us organize large amounts of information H We will talk about: array declaration.

Similar presentations


Presentation on theme: "Unit 5 1 Arrays and Vectors H Arrays and vectors are objects that help us organize large amounts of information H We will talk about: array declaration."— Presentation transcript:

1 unit 5 1 Arrays and Vectors H Arrays and vectors are objects that help us organize large amounts of information H We will talk about: array declaration and use arrays of objects multidimensional arrays the Vector class basic programming concepts object oriented programming topics in computer science syllabus

2 unit 5 2 Arrays H An array is an ordered list of values 0 1 2 3 4 5 6 7 8 9 79 87 94 82 67 98 87 81 74 91 An array of size N is indexed from zero to N-1 scores The entire array has a single name Each value has a numeric index This array holds 10 values that are indexed from 0 to 9

3 unit 5 3 Refering to Array Elements H A particular value in an array is referenced using the array name followed by the index in brackets  For example, the expression scores[2] refers to the value 94 (the 3rd value in the array)  scores[2] represents a place to store a single integer, and can be used wherever an integer variable can H For example, it can be assigned a value, printed, or used in a calculation

4 unit 5 4 Array Type H An array stores multiple values of the same type, primitive types or objects. Examples: an array of integers, an array of characters, an array of String objects H In Java, the array itself is an object. Therefore the name of the array is a object reference variable, and the array itself is instantiated separately

5 unit 5 5 Array Declaration  The scores array could be declared as follows: int[] scores = new int[10]; Note that the type of the array does not specify its size, but each object of that type has a specific size  The type of the variable scores is int[] (an array of integers) H It is set to a new array object that can hold 10 integers

6 unit 5 6 public class BasicArray { final static int LIMIT = 15; final static int MULTIPLE = 10; //-------------------------------------------------- // Creates an array, fills it with integer values, // modifies one value, then prints them out. //---------------------------------------------------- public static void main (String[] args) { int[] list = new int[LIMIT]; 0 1 2 3 4... 11 12 13 14 list זכרון

7 unit 5 7 public class BasicArray { final static int LIMIT = 15; final static int MULTIPLE = 10; //-------------------------------------------------- // Creates aan rray, fills it with integer values, // modifies one value, then prints them out. //---------------------------------------------------- public static void main (String[] args) { int[] list = new int[LIMIT]; // Initialize the array values for (int index = 0; index < LIMIT; index++) list[index] = index * MULTIPLE; 0 10 20 30 40... 110 120 130 140 list 0 1 2 3 4... 11 12 13 14 זכרון

8 unit 5 8 public class BasicArray { final static int LIMIT = 15; final static int MULTIPLE = 10; //-------------------------------------------------- // Creates aan rray, fills it with integer values, // modifies one value, then prints them out. //---------------------------------------------------- public static void main (String[] args) { int[] list = new int[LIMIT]; // Initialize the array values for (int index = 0; index < LIMIT; index++) list[index] = index * MULTIPLE; 0 1 2 3 4... 11 12 13 14 0 10 20 30 40... 110 120 130 140 0 10 20 30 99 50 60 70 80 90 100 110 120 130 140 for (int index = 0; index < LIMIT; index++) System.out.print (list[index] + " "); System.out.println (); } } list[4] = 99; // change one array value 99 list זכרון מסך

9 unit 5 9 Examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750];

10 unit 5 10 Bounds Checking H Once an array is created, it has a fixed size H An index used in an array reference must specify a valid element: value must be within bounds (0 to N-1) H The Java interpreter will detect an error if an array index is out of bounds; this is called automatic bounds checking

11 unit 5 11 Bounds Checking  For example, if the array codes can hold 100 values, it can only be indexed using the numbers 0 to 99  If count has the value 100, the Jave interpretter will give the message “ Array Out Of Bounds ” H It’s common to introduce off-by-one errors when using arrays: int[] codes = new int[100]; for (int index=1; index <= 100; index++) codes[index] = index*50 + epsilon; problem

12 unit 5 12 Number of array elements  Each array object has a public constant called length that stores the size of the array H It is referenced using the array name (just like any other object): scores.length  Note that length holds the number of elements, not the largest index

13 unit 5 13 // ReverseNumbers.java public class ReverseNumbers { //----------------------------------------------------------------- // Reads a list of numbers from the user, storing them in an // array, then prints them in the opposite order. //----------------------------------------------------------------- public static void main (String[] args) { System.out.println (); } double[] numbers = new double[10]; System.out.println ("The size of the array: " + numbers.length); for (int index = 0; index < numbers.length; index++) numbers[index] = EasyInput.getDouble("Enter next number"); System.out.println ("The numbers in reverse:"); for (int index = numbers.length-1; index >= 0; index--) System.out.print (numbers[index] + " ");

14 unit 5 14 Array Declarations Revisited H The brackets of the array type can be associated with the element type or with the name of the array H Therefore the following declarations are equivalent: float[] prices; float prices[]; H The first format is generally more readable

15 unit 5 15 Shortcut: Initializer Lists H An initializer list can be used to instantiate and initialize an array in one step H The values are delimited by braces and separated by commas H Examples: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', 'F'};

16 unit 5 16 Initializer Lists H Note that when an initializer list is used: the new operator is not used no size value is specified H The size of the array is determined by the number of items in the initializer list H An initializer list can only be used in the declaration of an array

17 unit 5 17 Arrays of Objects H The elements of an array can be object references  The following declaration reserves space to store 25 references to String objects String[] words = new String[25];  It does not create the String objects themselves H Each object stored in an array must be instantiated separately

18 unit 5 18 // GradeRange.java public class GradeRange { //----------------------------------------------------------------- // Stores the possible grades and their numeric lowest value, // then prints them out. //----------------------------------------------------------------- public static void main (String[] args) { String[] grades = {"A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F"}; int[] cutoff = {95, 90, 87, 83, 80, 77, 73, 70, 67, 63, 60, 0}; for (int level = 0; level < cutoff.length; level++) System.out.println (grades[level] + "\t" + cutoff[level]); } } A95 A-90 B+87 B83 B-80 C+77 C73 C-70 D+67 D63 D-60 F0

19 unit 5 19 A A B - String[] grades { Organizing array of objects in memory …

20 unit 5 20 Array of objects Coin[] dimes = new Coin[10]; int face; face = dimes[1].getFace(); X dimes[1] = new Coin(); face = dimes[1].getFace();

21 unit 5 21 Command-Line Arguments  The signature of the main method indicates that it takes an array of String objects as a parameter public static void main (String[] args) H These values come from command-line arguments that are provided when the interpreter is invoked  For example, the following invocation of the interpreter passes an array of three String objects into main: > java VoteRecount Florida New-Mexico Oregon H These strings are stored in args[0], args[1] and args[2] respectively

22 unit 5 22 Array members of Objects H Objects can have arrays as instance variables H Therefore, fairly complex structures can be created simply with arrays and objects H The software designer must carefully determine an organization of data and objects that makes sense for the situation

23 unit 5 23 Arrays as Parameters H A reference to an array can be passed to a method as a parameter H Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other H As the method access the array through an alias reference, the content of the array can be changed H An array element can be passed to a method like any other value

24 unit 5 24 Example: class Polynom // A polynom is a real valued function of the // form f(x)=a 0 +a 1 x+a 2 x 2 +...+a n x n. public class Polynom { // The coefficients of the polynom // coefficients[i] is the coefficient of x i private double[] coefficients; // Constructs a polynom with a given set // of coefficients. public Polynom(double[] coefficients) { this.coefficients = new double[coefficients.length]; for (int i=0; i<coefficients.length; ++i) this.coefficients[i] = coefficients[i]; }

25 unit 5 25 Class Polynom service method 1 // Computes the value of the polynom for given point // @return: the value of the polynom at x public double valueAt(double x) { double value = 0.0; double power = 1.0; for (int i=0; i<coefficients.length; i++) { value += coefficients[i]*power; power *= x; } return value; }

26 unit 5 26 Class Polynom service method 2 // Returns the degree of the polynom public int getDegree() { int degree = coefficients.length-1; while (coefficients[degree]==0.0) { degree--; } return degree; }

27 unit 5 27 Class Polynom service method 3 // Computes the polynom resulting from the addition // of this polynom and another polynom. public Polynom add(Polynom p) { return new Polynom(coeffs); } int degree = Math.max(getDegree(), p.getDegree()); int degmin = Math.min(getDegree(), p.getDegree()); double[] coeffs = new double[degree]; for (int i=0; i<degmin; i++) coeffs[i] = coefficients[i] + p.coefficients[i]; for (int i=degmin; i<degree; i++) if (getDegree()<p.getDegree()) coeffs[i] = coefficients[i]; else coeffs[i] = p.coefficients[i];

28 unit 5 28 Using class polynom // Prints a table of values for x 3 -2x 2 +5x+7; class PolynomUseExample { static final double LOWER_LIMIT = -5.0; static final double UPPER_LIMIT = 5.0; static final double STEP = 1.0; public static void main(String[] args) { double[] coefficients = {7.0, 5.0, -2.0, 1.0}; Polynom p = new Polynom(coefficients); for (double x=LOWER_LIMIT; x<=UPPER_LIMIT; x+=STEP) System.out.println(x + ” \t “ + p.valueAt(x)); } }

29 unit 5 29 Two-Dimensional Arrays H A one-dimensional array stores a simple list of values H A two-dimensional array can be thought of as a table of values, with rows and columns H A two-dimensional array element is referenced using two index values H To be precise, a two-dimensional array in Java is an array of arrays

30 unit 5 30 Array of arrays double[][] samples; samples = new double[6][]; samples[0] = new double[2]; samples[1] = new double[1]; for (int i=2; i<samples.length; i++) samples[i] = new double[i+1];

31 unit 5 31 class Table2D { public static void main(String[] args) { int[][] table2D = new int[4][]; table2D[0] = new int[7]; table2D[1] = new int[6]; table2D[2] = new int[8]; table2D[3] = new int[7]; for (int j=0; j<table2D.length; j++) { for (int i=0; i<table2D[j].length; i++) System.out.print(table2D[j][i]); System.out.println(); } } } 47687

32 unit 5 32 Two dimensional array double[][] samples; samples = new double[6][6];

33 unit 5 33 Example: class Matrix // A matrix of real numbers public class Matrix { // The elements of the matrix private double[][] elements; // Construct new matrix from table of values public Matrix(double[][] elements) { int height = elements.length; int width = elements[0].length; this.elements = new double[height][width]; for (int i=0; i<height; ++i) for (int j=0; j<width; ++j) this.elements[i][j] = elements[i][j]; } }

34 unit 5 34 Class Matrix service methods // Returns the number of rows of the matrix public int numberOfRows() { return elements.length; } // Returns the number of columns of the matrix public int numberOfColumns() { return elements[0].length; } // Returns element (i,j) of the matrix public double getElement(int i, int j) { return elements[i][j]; }

35 unit 5 35 Class Matrix service methods Class Matrix service methods public Matrix multiply(Matrix a) { int n = numberOfRows(); int m = numberOfColumns(); int l = a.numberOfColumns(); double[][] result = new double[n][l]; for (int i=0; i<n; i++) { for (int j=0; j<l; j++) { for (int k=0; k<m; k++) { result[i][j] += elements[i][k]*a.elements[k][j]; } } } return new Matrix(result); }

36 unit 5 36 Example: using class matrix class MatrixUse { public static void main(String[] args) { double[][] aElements = { { 1.0, 2.0}, {-3.0, 1.0} }; double[][] bElements = { { 3.0,-1.0}, {-2.0, 2.0} };

37 unit 5 37 Example: using class matrix Matrix a,b,c; a = new Matrix(aElements); b = new Matrix(bElements); c = a.multiply(b); for (int i=0; i<c.numberOfRows(); i++) { for (int j=0; j<c.numberOfColumns(); j++) { System.out.print(c.getElement(i,j)+” ”); } System.out.println(); } } }

38 unit 5 38 Multidimensional Arrays H An array can have as many dimensions as needed, creating a multidimensional array H Each dimension subdivides the previous one into the specified number of elements  Each array dimension has its own length member H Because each dimension is an array of array references, the arrays within one dimension could be of different length

39 unit 5 39 The Vector Class  An object of class Vector is similar to an array in that it stores multiple values H However, a vector only stores objects does not have the indexing syntax that arrays have  The methods of the Vector class are used to interact with the elements of a vector  The Vector class is part of the java.util package  See Beatles.java (page 304) Beatles.java

40 unit 5 40 The Vector Class H An important difference between an array and a vector is that a vector can be thought of as a dynamic, able to change its size as needed H Each vector initially has a certain amount of memory space reserved for storing elements H If an element is added that doesn't fit in the existing space, more room is automatically acquired


Download ppt "Unit 5 1 Arrays and Vectors H Arrays and vectors are objects that help us organize large amounts of information H We will talk about: array declaration."

Similar presentations


Ads by Google