Download presentation
Presentation is loading. Please wait.
Published byGeoffrey Chambers Modified over 8 years ago
1
L EC. 05: A RRAYS 0
2
C ONTENT Features of arrays Declaring, creating and using arrays Enhanced for -construct Variable length parameter-list 1
3
A RRAYS An array ( 陣列 ) is a contiguous memory space with fixed size used to store a group of data with compatible data type. An array is the simplest and basic data structure ( 資料 結構 ) used to store one or more logical-related data. An array can be used to store all the objects representing the students of a department. An array can be used to store all the objects representing the employees of a company. Arrays support random access ( 隨機存取 ). 2
4
A RRAYS IN J AVA An array is a collection of variables of the compatible type, referred to by a common identifier. Each individual variable is called an element ( 元素 ). Java only supports one-dimensional arrays. Java supports mechanism, called array-of-arrays, for building multi-dimensional arrays from one-dimensional arrays. Arrays are used for a variety of purposes because they offer a convenient means of grouping together related variables. Using an array to hold the records of all the students in a class. Each array is an object. The class of an array object is automatically created by Java platform. 3
5
D ECLARING ARRAYS Syntax form for declaring an array []; or [] ; The is the type of array elements, so called the base type. Example String strs[], addresses[], str; // str is not an array int[] vector, score; // both vector and list are arrays As arrays are objects in Java, the variables declared as arrays are reference variables referred to objects which represent arrays. When an array is declared, the array is not created. 4
6
C REATING ARRAYS An array is created by using the new operator with the following form. new [ ]; Example new String[10] new int[10*2] The must be an int-expression representing the number of elements in the array. The new operator dynamically allocates memory for an array and returns the reference of the array. Array declaration and creation can be combined into a single statement. String strs[] = new String[10]; The length of an array cannot be changed once it is created. 5
7
L ENGTH OF AN ARRAY The length of an array is the number of data item can be stored in the array. Each array has a instance field named length to represent the length of the array. The length field is final. A final field in Java is a field that can be set only once. Setting the length field of an array is illegal. Example The output of the following segment is 10. 6 int vector[] = new int[10]; System.out.println(vector.length);
8
A CCESSING ARRAY ELEMENTS Each individual element within an array is accessed by using an index( 索引 ). An index describes the position of an element within an array. In Java, all arrays have zero as the index of their first element. This index style is called zero-index. The type of indices must be compatible to int. To access an array element, specify the index of the element you want, surrounded by square brackets. Syntax form [ ] Example strs[0] = “Hello”; vector[3] = vector[0] + vector[2]; 7
9
A CCESSING ARRAY ELEMENTS The must be an int -expression. The value of must be within the range [0, length – 1], where length is the number of elements in an array. If the is out of bound, an exception (run-time error) occurs. The best way to process array elements is to use the for - construct. Example Let nums be an int array, then the following segment can find the maximum and minimum elements in nums. int min, max; min = max = nums[0]; for(int i = 1; i < nums.length; i++) { if(min > nums[i]) min = nums[i]; if(max < nums[i]) max = nums[i]; } 8
10
I NITIALIZING ARRAYS Syntax form 1 = { }; Syntax form 2 = new []{ }; The initializers are separated by using comma. The length of an array is determined by the number of initializers. The length cannot be specified if an initializer is given. Example String strs[] = {“hello”, “an”, “example”}; //legal String strs[]; strs = {“hello”, “an”, “example”}; //illegal int vector[] = new int[]{1, 2, 3, 4, 5, 6}; //legal int vector[]; vector = new int[]{1, 2, 3, 4, 5, 6}; //legal 9
11
E XAMPLE OF PROCESSING ARRAYS : BUBBLE SORTING Bubble sorting is a simple, but may not be efficient for large size arrays, sorting method. Bubble sorting proceeds iteratively. In the i th iteration Comparing the adjacent pair of elements, starting from the right-most two elements, and swapping them if they are out of order Stopping the iteration when the (i-1) th element is compared 10
12
F IGURE OF BUBBLE SORTING ( FIRST ITERATION ) 11
13
C LASS FOR SORTING class Sorting { public static int[] bubbleSort( int[] vector ) { // a class method int sorted[]; // declare an array sorted = new int[vector.length]; // create an array //duplicating vector to sorted System.arraycopy(vector, 0, sorted, 0, vector.length); for(int i = 1; i < sorted.length; i++) { for(int j = sorted.length – 1; j >= i; j--) { // ith iteration if(sorted[j–1] > sorted[j]) { //out of order, swap them int temp = sorted[j]; sorted[j] = sorted[j–1]; sorted[j–1] = temp; } return sorted; } 12
14
M ORE EFFICIENT VERSION 13 class Sorting { public static int[] bubbleSort( int[] vector ) { // a class method boolean flag; int sorted[]; // declare an array sorted = new int[vector.length]; // create an array //duplicating vector to sorted System.arraycopy(vector, 0, sorted, 0, vector.length); loop: for(int i = 1; i < sorted.length; i++) { // label it flag = true; for(int j = sorted.length – 1; j >= i; j--) { // ith iteration if(sorted[j–1] > sorted[j]) { //out of order, swap them flag = false; int temp = sorted[j]; sorted[j] = sorted[j–1]; sorted[j–1] = temp; } if(flag) break loop; // stop earlier } return sorted; }
15
M ULTIDIMENSIONAL ARRAYS In Java, a multidimensional array is implemented by using the concept of array of arrays. In a 2-dimensional array, i.e. a matrix( 矩陣 ), each row can be treated as a 1-dimensional array. So, a 2-dimensional array with m rows can be treated as a set of m 1-dimensional arrays. A 2-dimensional array can be implemented as a 1- dimensional array in which each element is a 1- dimensional array. The concept for implementing 2-dimensional arrays can be easily extended to any n-dimensional arrays. 14
16
D ECLARING MULTIDIMENSIONAL ARRAYS Syntax form [][]…[]; Example String empSkill[][]; // a 2-dimensional array int cube[][][]; // a 3-dimensional array 15
17
C REATING REGULAR MULTIDIMENSIONAL ARRAYS Syntax form new [ ][ ]…[ ] Example empSkill = new String[10][2]; Cube = new int[8][4][10]; 16
18
C REATING IRREGULAR MULTIDIMENSIONAL ARRAYS In Java, you can create upper-level arrays and then create lower-level arrays separately. Before upper-level array is created, no lower-level array can be created. Example 1 17 int matrix[][]; matrix = new int[3][]; // matrix = new int[][10]; is illegal matrix[0] = new int[4]; matrix[1] = new int[8]; matrix[2] = new int[6];
19
C REATING IRREGULAR MULTIDIMENSIONAL ARRAYS Example 2 18 int cube[][][]; cube = new int[2][][]; //create one 1-dimensional array with 2 elements // cube = new int[2][][10]; is illegal cube[0] = new int[2][3]; // totally create 3 1-dimensional arrays cube[1] = new int[3][]; // create one 1-dimensional array with 3 elements cube[1][0] = new int[2]; // create one 1-dimensional array with 2 elements cube[1][1] = new int[3]; // create one 1-dimensional array with 3 elements Cube[1][2] = new int[2]; // create one 1-dimensional array with 2 elements
20
L ENGTH OF ARRAYS Based on the examples on pages 17 and 18 matrix.length equals 3. matrix[1].length equals 8. matrix[1][0].length is illegal since matrix[1][0] is not an array. cube.length equals 2. cube[1].length equals 3. cube[0][2].length equals 2. Remember that. can access the instance field of an object pointed by a reference variable. Since matrix and matrix[1] points to array objects, matrix.length and matrix[1].length read the lengths of array objects. Since matrix[1][0] is int, matrix[1][0].length is illegal. 19
21
A CCESSING ELEMENTS OF MULTIDIMENSIONAL ARRAY For multidimensional arrays, each dimension needs a separate index set. To access an element of a multidimensional array, you need to specify the index for each dimension. Syntax form [ ][ ]…[ ] Example matrix[0][0] = matrix[1][1] + matrix[2][1]; cube[0][1][2] = 3 * cube[2][1][0]; 20
22
I NITIALIZING MULTIDIMENSIONAL ARRAYS A multidimensional array can be initialized by enclosing each dimension’s initializer list within its own set of curly braces. Example 21 String empSkill[][] = { {“John”, “Mary”, “Ken”}, // for empSkill[0] {“Network”, “Security”, “OS”} // for empSkill[1] } int cube[][][] = { { {1}, // cube[0][0][0] is 1 {1, 2} // cube[0][1][0] is 1, cube[0][1][1] is 2 }, { {22, 21, 34}, // cube[1][0][0] is 22 {30, 1}, // cube[1][1][1] is 1 {85, 34, 22, 56} // cube[1][2][3] is 56 }
23
E XAMPLE OF USING 2- DIMENSIONAL ARRAYS : MANIPULATING MATRICES class Matrix { int matrix[][]; Matrix(int noRow, int noCol) { //constructor matrix = new int[noRow][noCol]; //create a 2-dim array to represent the matrix for(int i = 0; i < noRow; i++) { // initialize the matrix for(int j = 0; j < noCol; j++) { matrix[i][j] = 0; } Matrix(int[][] arr) { // convert a 2-dimensional array to a Matrix object matrix = new int[arr.length][]; for( int i = 0; i < arr.length; i++) { matrix[i] = new int[arr[i].length]; System.arraycopy(arr[i], 0, matrix[i],0, arr[i].length); // copy the ith row } public void setElement(int row, int col, int val) { matrix[row][col] = val; } public int getElement(int row, int col) { return matrix[row][col]; } 22
24
E XAMPLE OF USING 2- DIMENSIONAL ARRAYS : MANIPULATING MATRICES public void add(Matrix addend) { // add addend to this object for(int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[i].length; j++) { matrix[i][j] += addend[i][j]; } public void printMatrix() { // print this object in matrix form for( int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j]+” “); } System.out.println(); } 23
25
F OR - EACH STYLE for - CONSTRUCT Beginning with J2SDK v. 1.5, Java supports a new for-each style for -construct, so called enhanced for -construct. The enhanced for -construct cycles through a collection of objects, such as an array, in strictly sequential fashion, from start to finish. Syntax form for( : ) statement; The specifies the type of. The specifies the name of an iteration variable that will receive the elements from, one at a time, from beginning to end. The collection being cycled through is specified by. There are various types of collections, such as primitive and class types, that can be used with the for. 24
26
F OR - EACH STYLE for - CONSTRUCT The base type of must be compatible with the type of iteration variable. With each iteration of the loop, the next element in the collection is retrieved and stored in. The loop repeats until all elements in the collection have been obtained. Its iteration variable is “read-only” as it relates to the underlying array. An assignment to the iteration variable has no effect on the underlying array. Example The following segment can add up all the data in a int array name nums. 25 int sum = 0; for(int var : nums) { sum += var; }
27
F OR - EACH STYLE for - CONSTRUCT Since the type of can be arrays, the enhanced for -construct can also apply to process multidimensional arrays as the following example. Example Let matrix be a 2-dimensional array. 26 int sum = 0; for(int row[]: matrix) { for(int val : row) { sum += val; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.