Download presentation
Presentation is loading. Please wait.
1
For use of IST410 Students only Arrays-1 Arrays
2
For use of IST410 Students only Arrays-2 Objectives l Declaring arrays l Instantiating arrays l Using arrays as parameters l One and multi-dimensional arrays l A few array utilities
3
For use of IST410 Students only Arrays-3 Arrays: Introduction l Concept of array is not unique to Java; all modern programming languages support arrays l Arrays exist in C, C++, Pascal, and other languages l In COBOL, tables with exactly one field type are arrays l Suppose we are interested in representing the result of a survey that has exactly one question and 200 responses m We could declare 200 variables: resp0, resp1, resp2,...,resp199 m Or, we could declare an array with 200 elements, each element representing a response m If the name of the array is resp, then its elements are resp[0], resp[1], resp[2],...,resp[199] m Notice that indexes go from 0 to 199, one less than the array size
4
For use of IST410 Students only Arrays-4 Arrays: Introduction l An array index need not be a constant, it can be a variable or an expression that yields an integer value int i; // other statements i = 118; resp[i] = 20; //20 is being assigned to the 119th // element of the resp array l The data type of an array can be any legal data type i.e both primitive and object types l Arrays group objects of the same data type i.e all elements of an array are of same type
5
For use of IST410 Students only Arrays-5 Declaring Arrays l In Java, arrays are objects l Array objects are created in two steps: m Declare an array reference m Construct the array instance l Declaration int m[];or int [] m; Point p[];orPoint [] p; l Declaration leads to space allocation for one reference variable: space for m in the case of the int array and space for p for the other l Space is allocated for elements of the array only after the array is instantiated
6
For use of IST410 Students only Arrays-6 Instantiating Arrays l Arrays need to be instantiated before they can be used l Arrays with primitive data types m = new int[20]; l Array of objects p = new Point[20]; p[0] = new Point(); // objects need to be constructed m 0 1 2 19 p space for array elements Object references only
7
For use of IST410 Students only Arrays-7 Instantiating Arrays l Array elements are automatically initialized when the array is instantiated l The initial value depends on the data type of the array elements values of m are set to 0 since the type is int values of p are set to null since these are references l An array can be explicitly initialized at declaration int [] m = {1, 23, -2, 0, 12}; Point [] p = { new Point(1,1), new Point(2,3), new Point(3,5)}; String [] s = {“IST203”,”IST211”,”IST221”};
8
For use of IST410 Students only Arrays-8 Traversing Arrays l Arrays are often traversed using loops l We can set up a loop to traverse through an array for (int i = 0; i < 20; i++) { System.out.println(“Element “+i+”=“+m[i]); } l Use of fixed numbers like 20 is potentially error prone since it is illegal to exceed the boundary of an array l All arrays know their lengths; we can use this feature to traverse any array
9
For use of IST410 Students only Arrays-9 Traversing Arrays l The count of array elements is stored in the array’s length attribute l We can traverse the array using the value of length to control for array boundaries for (int i = 0; i < m.length; i++) { System.out.println(“Element “+i+”=“+m[i]); } l Traversing an array using the length attribute is a safe technique
10
For use of IST410 Students only Arrays-10 Copying Arrays l Need to copy an array arises in many applications l We can try to copy an array using the following int [] a = {1,2,3,4,5}; int [] b = a; l Notice that we did not duplicate the array, but copied the reference only; both a and b refer to the same array b a1 2 3 4 5
11
For use of IST410 Students only Arrays-11 Copying Arrays l Arrays can be copied using System.arraycopy System.arraycopy(a, 0, b, 0, a.length); l The general syntax of arraycopy System.arraycopy(source array, source index, target array, target index, # of elements); a b 1 2 3 4 5
12
For use of IST410 Students only Arrays-12 Comparing Arrays l Consider the following two arrays int [] b = {1,2,3,4,5}; int [] c = {1,2,3,4,5}; if (b = = c) System.out.println(”b and c are same arrays"); else System.out.println(”b and c are different arrays"); l Unfortunately, in the above statement, b would be found not equal to c l We are comparing references; b and c refer to TWO DIFFERENT objects, hence unequal
13
For use of IST410 Students only Arrays-13 Comparing Arrays l We can compare arrays using the equals method import java.util.Arrays; int [] b = {1,2,3,4,5}; int [] c = {1,2,3,4,5}; if (Arrays.equals(b,c)) System.out.println(”b and c are same arrays"); else System.out.println(”b and c are different arrays"); l Contents of arrays are compared when Arrays.equals is used l java.util.Arrays provides a number of overloaded equals method to compare arrays of different types
14
For use of IST410 Students only Arrays-14 Multidimensional Arrays l Java arrays can be multidimensional l A multidimensional array is an array of arrays l For example, an array that has 3 rows and 5 columns can be shown as the following l We need 2 different indexes to designate an individual cell
15
For use of IST410 Students only Arrays-15 Multidimensional Arrays l As in the case of one dimensional arrays, creation of a multidimensional array is a two-step process int [][] p; p = new int[4][]; l Since the second dimension of p is undefined, elements of p need to be defined one at a time p[0] = new int[5]; p[1] = new int[5]; and so on l The size of a multidimensional array may be completely defined at declaration int [][] p = new int[4][5]; // 4 rows and 5 columns
16
For use of IST410 Students only Arrays-16 Multidimensional Arrays l It is illegal to leave first dimension empty in the declaration of a multidimensional array int [][] m = new int[][5]; // does not compile l When instantiated, elements of an array are automatically initialized to the appropriate default value based on the array’s data type l In our example, p is an int array. All elements of p are initially set to 0. l For an array of objects, elements would be initialized to null
17
For use of IST410 Students only Arrays-17 Multidimensional Arrays l Multidimensional arrays can be initialized at declaration int [][] m = { {1,2,3}, {4,5,6,7}, {8,9,10,11}}; l A multidimensional array of objects is declared using the familiar syntax Point [][] pt = new Point[5][10]; l Each cell of pt then is a reference and and objects themselves need to be instantiated pt[0][0] = new Point(); pt[0][1] = new Point();
18
For use of IST410 Students only Arrays-18 Multidimensional Arrays l A multidimensional array need not be rectangular l For example, a twodimensional array can be non- rectangular as shown below int [][] m = new int[4][]; m[0] = new int[5]; m[1] = new int[6]; m[2] = new int[10]; m[3] = new int[12];
19
For use of IST410 Students only Arrays-19 Multidimensional Arrays l A multidimensional array can be traversed using length attribute for (i = 0; i < m.length; i++) for (j = 0; j < m[i].length; j++) System.out.println(“Element = “+m[i][j]); l Notice that so long as the length attribute of an array is used, traversing a non-rectangular array is not a problem
20
For use of IST410 Students only Arrays-20 Arrays as Parameters public class ArraySearch { //ArraySearch.java public static void main(String args[]) { char [] c = {'A','C','D','E','F','H','K','J'}; int index = ArraySearch.find(c,'F'); if (index == -1) System.out.println("Search character not found"); else System.out.println("F is at index position "+index); } public static int find(char[]t, char s){ int index = 0; int location = -1; while (index < t.length && location == -1) { if (t[index] == s){ location = index; } index++; } return location; } Note the declaration of array parameter in the method find, and also how arrays are passed into a method
21
For use of IST410 Students only Arrays-21 Sorting one dimensional arrays l An array can be sorted as follows import java.util.Arrays; int []m = {1,2,45,56,78,34,8,-1}; Arrays.sort(m); l Sorted array is in ascending order l A number of overloaded sort methods are available l sort method can be applied to one dimensional arrays only
22
For use of IST410 Students only Arrays-22 Binary search: one dimensional Arrays l Binary search for a value int []m = {1,2,45,56,78,34,8,-1}; Arrays.sort(m); int r = Arrays.binarySearch(m,8); if (r < 0) System.out.println(“Item not found”); else System.out.println(“Item at “+r); l If the item searched for is in the list, the correct index is returned l If r is negative, the item does not exist in the list. An index equal to (-r-1) represents the index where the value can be inserted to keep the array sorted
23
For use of IST410 Students only Arrays-23 Exercise l Write a MyArray class that uses a one-dimensional array of 100 elements. This array has the following methods: m a constructor that initializes the elements to a random integer between 10 and 140 m a method that returns the average of all elements of the array m a method that returns the sum of all elements l Write a MyTwodArray class that uses a two-dimensional array. This array has the following methods m a constructor that initializes the elements to a random character m a method that takes 2 arguments: a row index and a search character and returns the number of times this character occurs in the row m To be more challenging, take the 2 dimensional array sizes as command line arguments and test to make sure that these sizes are in fact read in as arguments before proceeding further
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.