Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
An Introduction to Programming and Object Oriented Design using Java 2rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 13 – Arrays Anatomy of an array Indices a contiguous sequence of variables. all of the same type. Each variable is identified by its index. Index values are integers. Index of first entry is 0. 0 1 2 3 Variables 4 5 6 7 8 9 10 11 Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 1 Arrays Structure composed of contiguous sequence of variables, all of the same type. Type of array element primitive type (char, int, boolean, double, etc.) or reference type (Student, PlayingCard, Object, etc.) Length of array: number of component variables If length of array is n, index range from 0 to n-1. length of array is fixed after creation. Access of an array variable is in constant time Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 2 Arrays They are subclass of Object. Have a public final int component length. int[] denotes the class array-of-int, Student[] denotes the class array-of-Student. Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 3 Defining arrays Creates an array-of-int named grades int[] grades; Student[] cs2125; Creates an array-of-Student named cs2125. Note: declaring the variable does not create an array. grades cs2125 Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 4 Defining arrays grades = new int[5]; cs2125 = new Student[5]; create two arrays of length 5, and assign references to specified variables Student[ ] int[ ] grades Dec 2007 0 1 2 3 4 0 0 0 0 0 length 5 cs2125 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 0 1 2 3 4 length 5 5 Accessing array components grades[3] It’s an int variable We can also write: grades[3] = 100; grades[4] = grades[3]/2; Similarly, we can write: cs2125[0] = new Student(…); cs2125[0].payFees(100); Important: index value used to access an array variable must be in range 0 to length of array - 1 Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 6 Initializing array variables Can assign each component of array grades 100 via: for (int i = 0; i < grades.length; i = i+1) grades[i] = 100; Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 7 ArrayIndexOutOfBoundsException Array index: negative or greater than or equal to array length results in run-time error: ArrayIndexOutOfBoundsException. for (int i = 0; i <= grades.length; i = i+1) grades[i] = 100; Stores value 100 in all components of array grades, but fails on last iteration when i equals grades.length with error ArrayIndexOutOfBoundsException Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 8 Example: Average public double average (int[] numbers) { assert numbers.length > 0; int i; // index into array int sum; // sum = 0; for (i = 0; i < numbers.length; i = i+1) sum = sum + numbers[i]; return (double)sum / (double)numbers.length; } Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 9 Example: Searching an array public int indexOf (Object item, Object[] array) { int i = 0; // index of next element to examine while (i < array.length && !array[i].equals(item)) i = i+1; if (i < array.length) return i; // item found else return -1; // item not found } Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 10 Example: Inserting an entry in an array Insert 1 into vector array at index 0. Idea : shuffle down existing values and insert new element in “vacated” space: 0 1 2 3 4 Dec 2007 0 2 4 6 8 insert(1,vector) 0 1 2 3 4 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 1 0 2 4 6 11 Example: Inserting an entry in an array “shuffling” must be done starting with largest indexed element to be moved—the element with index 3 below. Incorrectly done if we write for (int i = 0; i < vector.length; i = i+1) vector[i+1] = vector[i]; 0 1 2 3 4 0 2 4 6 8 i == 0 Dec 2007 0 1 2 3 4 0 0 4 6 8 0 1 2 3 4 i == 1 0 0 0 6 8 i == 2 0 1 2 3 4 0 0 0 0 8 0 1 2 3 4 0 0 0 0 0 i == 3 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 12 Example: Inserting an entry in an array public void insert (int newValue, int[] vector) { assert vector.length > 0; // i indexes the next value to move for (int i = vector.length-2; i >= 0; i = i-1) vector[i+1] = vector[i]; vector[0] = newValue; } Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 13 Example: Reversing an array 0 1 2 3 4 Dec 2007 A B C D E 0 1 reverse(array); 2 3 4 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java E D C B A 14 Example: Reversing an array Iteratively interchange pairs until array is reversed. 0 1 2 3 4 Dec 2007 A B C D E 0 1 2 3 4 E B C D A 0 1 2 3 4 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java E D C B A 15 Example: Reversing an array public void reverse (Object[] array) { int low = 0; int high = array.length-1; low <not high all positioned ) { while ( elements swap(array, low, high); low = low+1; high = high-1; } } private void swap (Object[] array, int i, int j) { Object temp = array[i]; array[i] = array[j]; array[j] = temp; } Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 16 Reading into an array from an input stream Issues to consider: Size of array is fixed when created. Need to know max number of values to read before hand. Need to have a way to determine all values in input stream have been read. Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 17 Reading into an array from an input stream Three possibilities to know all values in input stream have been read. Know number of values to be read. Input stream contains a sentinel to indicate all values have been read. Read until input stream has been exhausted. Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 18 Reading into an array from an input stream States of an input stream There is data remaining to be read. There is no data in input stream, stream is not closed. Input stream is closed. No more data will appear. Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 19 Reading into an array from an input stream Dealing with pre-determined array size. Knowing maximum number of values to be read, keep track of actual number read. private int[] grades; private int gradeCount; // exam grades // number of exam grades 0 Contain valid grades read gradeCount Contain undefined values Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 20 Reading into an array from an input stream There are more data values than array elements: Consider it an error. Read as many values into array as possible, ignore rest. Create a new larger array, copy values from old array into new one. For readGrades method we assume: Method has parameter that gives maximum grades to read. Read from standard input until all data is exhausted or Until maximum number of grades has been read. Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 21 Reading into an array from an input stream /** * Read exam grades from standard input. Grades will * be read until either maxGrades are read, or end of * file is encountered. * @require maxGrades > 0 * tokens in standard input are decimal * integers separated by white space. */ public void readGrades (int maxGrades) { assert maxGrades > 0; grades = new int[maxGrades]; Scanner in = new Scanner(System.in); gradeCount = 0; while (gradeCount < maxGrades && in.hasNext()) { grades[gradeCount] = in.nextInt(); gradeCount = gradeCount + 1; } } Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 22 Constant Arrays. Date class Use a constant array to define the number of days in each month. private static final int[] daysInMonth = {0,31,28,31,30,31,30,31,31,30,31,30,31}; daysInMonth is static: it is associated with the class. final: cannot assigned a new value to daysInMonth, but (beware) can change the array entries. Array has 13 entries rather than 12, as we want to index by the month number. February has 28 days. Will need to treat it as special case in the methods. Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 23 Date class: isLegalDate private static final int MIN_YEAR = 1763; private static final int JAN = 1; private static final int FEB = 2; private static final int DEC = 12; public static boolean isLegalDate ( int day, int month, int year) { int maxDay; boolean isLegal; if (year >= MIN_YEAR && JAN <= month && month <= DEC) { maxDay = daysInMonth[month]; if (month == FEB && isLeapYear(year)) maxDay = maxDay + 1; isLegal = (1 <= day && day <= maxDay); } else isLegal = false; // year or month is bad. return isLegal; } Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 24 Array with array components Components of an array can be of almost any type, in particular the can be arrays. int [ ] [ ] twoDArray; int [ ] 0 1 2 3 int [ ][ ] twoDArray length 0 1 2 3 length 4 int [ ] 4 0 1 2 length Dec 2007 0 0 0 0 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 0 0 0 3 25 Creating multi-dimensional arrays Given int[ ] [ ] twoDArray; The left most bracket indexes the object itself. Right most bracket indexes the components. twoDArray = new int[3][ ]; Creates array with 3 components, each int[ ] And each int [] initially null. int[ ][ ] twoDArray 0 1 2 length Dec 2007 3 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 26 Creating multi-dimentional arrays The components of twoDArray are of the same type int[], but not need be of same length. int[ ] int [ ][ ] matrix 0 0 0 0 length 4 0 1 2 length Dec 2007 0 1 2 3 3 int[ ] 0 1 2 3 0 0 0 0 length 4 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java int [ ] 0 1 2 3 0 0 0 0 length 4 27 Accessing multi-dimensional array components int[][] matrix = new int[4][3]; // set all twelve integer variables to 100 as follows. for (int i = 0; i < matrix.length; i = i+1) for (int j = 0; j < matrix[i].length; j = j+1) matrix[i][j] = 100 Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 28 Example: Tic-Tac-Toe Constructor creates board, initializes it to unmarked. public class TicTacToeGame { public static final int UNMARKED = 0; public static final int O = -1; public static final int X = 1; private int[][] board; private static final int SIZE = 3; … public TicTacToeGame () { board = new int[SIZE][SIZE]; clearBoard(); … } private void clearBoard () { for (int row = 0; row < SIZE; row = row+1) for (int col = 0; col < SIZE; col = col+1) board[row][col] = UNMARKED; NH-Chapter 13: Introduction To Programming And Dec 2007 Object Oriented Design Using Java } 29 Example: Tic-Tac-Toe Constructor creates board, initializes it to unmarked. private static final int NONE = 0; private int winner () { int winner = checkRows(); if (winner == NONE) checkColumns(); if (winner == NONE) checkDiagonals(); return winner; } private int checkRows () { int wins = NONE; for (int r = 0; wins == NONE && r < SIZE; r = r+1) { int sum = 0; for(int c = 0; c < SIZE; c = c + 1) sum = sum + board[r][c]; wins = sum/SIZE; } return wins; NH-Chapter 13: Introduction To Programming And 30 }Dec 2007 Object Oriented Design Using Java Types and Arrays: Component types An array cannot be created with a parameterized type as component type. The following is illegal: List<Student>[] classes = new List<Student>[10]; An array cannot be created with type parameter as component type. The following is illegal: public class DefaultList<Element> { … private Element[] elements = new Element[10]; … } Must declare elements to be an array of Objects, Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 31 Arrays and subtyping A B variable can contain any of these B values A values An A variable can contain only these public double totalArea (ClosedFigure[] figures) { double sum = 0.0; for (int i = 1; i < figures.length; i = i+1) sum = sum + figures[i].area(); return sum; } Can invoke with array of Circle, array of Square. Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 32 Array subtyping public void initializeGrid (ClosedFigure[ ] grid) { for (int i = 1; i < grid.length; i = i+1) grid[i] = new Square(1); } Circle[ ] multicsRings = … ; totalArea(muticsRings); initializeGrid(multicsRings); // legal invocation. // legal invocation, // but illegal effect. Java defines array-of-A to be a subtype of array-of-B if A is a subtype of B. (erroneously) Invocation of initializeGrid compiles, but a runtime error, ArrayStoreException, results attempting to execute grid[i] = new Square(1); Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 33 Modeling lists with arrays Brief look at some of the issues involved in implementing a class like ArrayList. Want to use an array to store the list elements. Questions: How are the list elements stored in the array? How many elements should the array contain? What happens if list grows larger than array? How to handle the fact that ArrayList is a generic class and can’t create an array with a type parameter as component type? Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 34 Modeling lists with arrays Allocate array to hold references to elements of list. array is a list component containing the list elements. Array component 0 references first element of list, component 1 references the second, and so on. Length of list is bounded by length of array, and array length is fixed when the array is created. Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 35 Modeling lists with arrays What should we do if an attempt is made to add an item to a full array? Can’t add a precondition to the add methods requiring list size less than some predetermined value. It strengthens List preconditions in the implementation, which is not allowed. Replace the array with a new larger array, and copy values from original array to new one. Creates new array 50% larger than original. Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 36 Modeling lists with arrays: entry type ArrayList is a generic class: public class ArrayList<Element> { …. } Want to declare array as an array-of-Element: private Element[ ] elements; That’s illegal. Must declare it array-of-Object. private Object[ ] elements; Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 37 Modeling lists with arrays: entry type Retrieving an element from array requires a cast public Element get (int index) { return (Element) this.elements[index]; } Cast generates a compilation “unchecked cast warning”. It alerts us to a possible cast error at runtime, which we must check to avoid!!! But, here, an item must be of type Element to be in list: public void add (Element element) public void add (int index, Element element) public set (int index, Element element) Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 38 Modeling lists with arrays: add, remove We need a private method to expand array when needed /** * Create a new elements array bigger than the current * one by the specified amount. * Copy values from current array to new. */ private void expand (int increase) { Object[] newElements = new Object[elements.length + increase]; //copy to new array: for (int i = 0; i < elements.length; i = i+1) newElements[i] = elements[i]; elements = newElements; } Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 39 add(int i, Element elm) implementation add(int,Element) shuffles portion of the array down. Example: list contains six elements, and a new element is to be inserted at index position 2. Entries at indices : 2,3,4,5 must be moved down, starting with the last, to make room for new element. Dec 2007 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 40 remove(int index) implementation remove(int) shuffles portion of the array up. Example: list contains six elements, and must remove element at index position 3 entries at indices : 4,5 must be moved up, starting with the the one at index 4. 0 1 2 3 4 size - 1 Dec 2007 5 A B 0 C D 2 E F 1 3 size - 1 4 5 6 6 7 7 8 8 9 9 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java A B C E F F 41 remove(int index) implementation In the remove method after shifting elements up in the array we place store a null value in the now unsed entry. It makes it easier for the runtime to remove unused space. remove(3); 0 1 2 3 4 5 6 7 8 9 Dec 2007 A B C D E F 0 1 2 3 move up 4 and 5 4 5 6 7 8 9 A B C E F F store null in 5 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 0 1 2 3 4 5 6 7 8 9 A B C E F 42 ArrayList implementation: add, remove public void add (int index, Element element) { if (size == elements.length) expand(size/2 + 1); //grow by at least one // make space for new element for (int i = size-1; i >= index; i = i-1) elements[i+1] = elements[i]; elements[index] = element; size = size+1; } public void remove (int index) { for (int i = index+1; i < size; i = i+1) elements[i-1] = elements[i]; // remove useless ref elements[size-1] = null; size = size-1; } Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 43 ArrayList implementation public Element get (int index) { return (Element)elements[index]; } public int indexOf (Element element) { int i = 0; while (i < size && !element.equals(elements[i]) i = i+1; if (i < size) return i; else return -1; } Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 44 Command line arguments public static void main (String[ ] args) { … } The argument to main is a String array, the elements of which are called command line arguments. The runtime system can use command line arguments to provide information to an application when the application is initiated. Example, if main method of a class Echo is run with the user command: java Echo Nothing to be done Command line arguments Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 45 Command line arguments public class Echo { public static void main (String[] args) { for (int i = 0; i < args.length; i = i+1) { System.out.println(args[i]); } } } User runs the application with the command java Echo Nothing to be done The following four lines of output will be produced: Nothing to be done Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 46 Command line arguments Command line arguments often used to provide configuration information when starting an application. java StudentRecords -restart current.log Might inform application StudentRecords to go through a “restart sequence,” reading from file named current.log. Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 47 Variable arity parameters The last (or only) parameter of a constructor or method can have an ellipsis (...) following the type. Such a parameter is called a variable arity parameter. public int count (char c, String... words) { … } Variable arity parameter Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 48 Variable arity parameters When a method or constructor with a variable arity parameter is invoked, the corresponding argument can simply be an array of the appropriate type. Example: invocation of count String[] stooges = {"Larry", "Curly", "Moe"}; int i = count ('x', stooges); results in parameter words referencing array stooges. Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 49 Variable arity parameters Method count can be invoked with any number of arguments corresponding to the variable arity parameter. The type of each of these arguments must match the base type of the parameter. int int int int Dec 2007 i i i i = = = = count('x'); count('x',"Shemp"); count('x',"Larry","Curly","Moe"); count('x',"Iggy","Ron","Scott","Mike"); NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 50 Variable arity parameters In the method body, the variable arity parameter is used like any other array variable. For instance, /** * Number of occurrences of specified character in words. */ public int count (char c, String... words) { int charCount = 0; for (int w = 0; w < words.length; w = w+1) for (int i = 0; i < words[w].length(); i = i+1) if (c == words[w].charAt(i)) charCount = charCount + 1; return charCount; } Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 51 Advantages and limitation of array implementations List elements can be accessed in constant time : get(int) add(Element) set(int,Element) The following operations are linear: remove(int) add(int,Element) indexOf(Element) Steps required (for add, remove) increases proportionally to size of list. On average, half the list must be shifted up or down to add or remove. Dec 2007 NH-Chapter 13: Introduction To Programming And Object Oriented Design Using Java 52