1 / 23

Arrays

Arrays. Objectives. Declaring arrays Instantiating arrays Using arrays as parameters One and multi-dimensional arrays A few array utilities. Arrays: Introduction. Concept of array is not unique to Java; all modern programming languages support arrays

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

  2. Objectives • Declaring arrays • Instantiating arrays • Using arrays as parameters • One and multi-dimensional arrays • A few array utilities

  3. Arrays: Introduction • Concept of array is not unique to Java; all modern programming languages support arrays • Arrays exist in C, C++, Pascal, and other languages • In COBOL, tables with exactly one field type are arrays • Suppose we are interested in representing the result of a survey that has exactly one question and 200 responses • We could declare 200 variables: resp0, resp1, resp2,...,resp199 • Or, we could declare an array with 200 elements, each element representing a response • If the name of the array is resp, then its elements are resp[0], resp[1], resp[2],...,resp[199] • Notice that indexes go from 0 to 199, one less than the array size

  4. Arrays: Introduction • 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 • The data type of an array can be any legal data type i.e both primitive and object types • Arrays group objects of the same data type i.e all elements of an array are of same type

  5. Declaring Arrays • In Java, arrays are objects • Array objects are created in two steps: • Declare an array reference • Construct the array instance • Declaration int m[]; or int [] m; Point p[]; or Point [] p; • 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 • Space is allocated for elements of the array only after the array is instantiated

  6. Instantiating Arrays • Arrays need to be instantiated before they can be used • Arrays with primitive data types m = new int[20]; • Array of objects p = new Point[20]; p[0] = new Point(); // objects need to be constructed space for array elements m 0 1 2 19 Object references only 0 1 2 19 p

  7. Instantiating Arrays • Array elements are automatically initialized when the array is instantiated • 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 • 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. Traversing Arrays • Arrays are often traversed using loops • 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]); } • Use of fixed numbers like 20 is potentially error prone since it is illegal to exceed the boundary of an array • All arrays know their lengths; we can use this feature to traverse any array

  9. Traversing Arrays • The count of array elements is stored in the array’s length attribute • 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]); } • Traversing an array using the length attribute is a safe technique

  10. Copying Arrays • Need to copy an array arises in many applications • We can try to copy an array using the following int [] a = {1,2,3,4,5}; int [] b = a; • Notice that we did not duplicate the array, but copied the reference only; both a and b refer to the same array a 1 2 3 4 5 b

  11. Copying Arrays • Arrays can be copied using System.arraycopy System.arraycopy(a, 0, b, 0, a.length); • The general syntax of arraycopy System.arraycopy(source array, source index, target array, target index, # of elements); 1 2 3 4 5 a b 1 2 3 4 5

  12. Comparing Arrays • 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"); • Unfortunately, in the above statement, b would be found not equal to c • We are comparing references; b and c refer to TWO DIFFERENT objects, hence unequal

  13. Comparing Arrays • 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"); • Contents of arrays are compared when Arrays.equals is used • java.util.Arrays provides a number of overloaded equals method to compare arrays of different types

  14. Multidimensional Arrays • Java arrays can be multidimensional • A multidimensional array is an array of arrays • For example, an array that has 3 rows and 5 columns can be shown as the following • We need 2 different indexes to designate an individual cell

  15. Multidimensional Arrays • As in the case of one dimensional arrays, creation of a multidimensional array is a two-step process int [][] p; p = new int[4][]; • 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 • The size of a multidimensional array may be completely defined at declaration int [][] p = new int[4][5]; // 4 rows and 5 columns

  16. Multidimensional Arrays • It is illegal to leave first dimension empty in the declaration of a multidimensional array int [][] m = new int[][5]; // does not compile • When instantiated, elements of an array are automatically initialized to the appropriate default value based on the array’s data type • In our example, p is an int array. All elements of p are initially set to 0. • For an array of objects, elements would be initialized to null

  17. Multidimensional Arrays • Multidimensional arrays can be initialized at declaration int [][] m = { {1,2,3}, {4,5,6,7}, {8,9,10,11}}; • A multidimensional array of objects is declared using the familiar syntax Point [][] pt = new Point[5][10]; • 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. Multidimensional Arrays • A multidimensional array need not be rectangular • 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. Multidimensional Arrays • 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]); • Notice that so long as the length attribute of an array is used, traversing a non-rectangular array is not a problem

  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. Sorting one dimensional arrays • An array can be sorted as follows import java.util.Arrays; int []m = {1,2,45,56,78,34,8,-1}; Arrays.sort(m); • Sorted array is in ascending order • A number of overloaded sort methods are available • sort method can be applied to one dimensional arrays only

  22. Binary search: one dimensional Arrays • 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); • If the item searched for is in the list, the correct index is returned • 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. Exercise • Write a MyArray class that uses a one-dimensional array of 100 elements. This array has the following methods: • a constructor that initializes the elements to a random integer between 10 and 140 • a method that returns the average of all elements of the array • a method that returns the sum of all elements • Write a MyTwodArray class that uses a two-dimensional array. This array has the following methods • a constructor that initializes the elements to a random character • 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 • 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

More Related