160 likes | 245 Vues
Arrays. Liang, Chpt 5. myName. 0. 1. 2. 3. 4. 5. Array of char s: each char in a numbered box. F. i. n. t. a. n. Each box’s number is called its index. arrays. An array is a data structure which stores several elements
E N D
Arrays Liang, Chpt 5
myName 0 1 2 3 4 5 Array of chars: each char in a numbered box. F i n t a n Each box’s number is called its index arrays • An array is a data structure which stores several elements • All elements are the same type (e.g. int, double, char, String....) For example, a String variable contains an array of characters: String myName = “Fintan”; creates a box like this in the computer’s memory: Array of chars public static int length(){…} public static boolean equal(String x){…} public static char charAt(int i){…} … These are some of the methods that Strings have (that the Stringclass has)
Why bother with arrays? • Many programs need to work with many numbers at once • E.g. a program to produce a telephone directory • Keeping track of many separate variables is tiresome and error prone • So we keep them all together, like peas in a pod • or beads on a string.....or socks in the sock drawer • or......................
scores 0 1 2 3 4 5 Example: keeping track of class scores We will store these numbers in an array of ints called scores next score: 87 next score: 62 next score: 45 next score: 64 next score: 30 next score: 88 87 62 45 64 30 88 When we create an array in a java program, Java sets aside an area of memory large enough to hold that array. The variable name for the array points at (holds the memory location of) that area of memory (e.g. scores above points at the array location) The memory space needed to hold an array depends on (1) how many elements there will be in the array, (2) how big the element type is
Declaring and creating an array int[] scores; // declaration scores = new int[6]; // creation int[] means “an array of integers”. int[] scores; means scores is the name for this array of integers. This first line just tells java that scores will point to (that is, hold the memory location of) an array of integers (ints). new int[6]means “set aside new memory space for an array of six ints”. new is a java command meaning “create a new space in memory for” scores = new int[6];tells java to set the variable scores so that it points to (has the memory address of) that newly created array.
0 1 2 3 4 5 0 0 0 0 0 0 scores Declaring and creating in one go // both together int[] scores = new int[6]; This sets aside memory space for an array of six ints, and sets the variable scores to point to that memory space. Now, we’ve (1) created an array variable, (2) created memory space for an array and (3) set the variable to point to that space. But we haven’t put anything into the array yet. Before anything is put into the boxes in an array, they are given a default value (zero for numbers). So our array looks like this:
Indexing into an array To refer to elements in an array, we use the array name and the index of the element we want. scores[0] = 87; scores[1] = 62; // and so on The first element is scores[0]. Since we created space for 6 elements in the scores array, the last element is scores[5]. Counting from 0 often gives people problems with arrays. Remember, for an array with X elements, the last element has the index X-1 Also, a variable called length gives us the total length of the array. // assigning some values to array elements String x; // to hold the users input for(int i=0; i<scores.length; i++) { x=JOptionPane.showInputMessage(null,”enter score “+i); scores[i] = Integer.parseInt(x); }
Quick declaration, creation and initialization double[] myList = {1.9, 2.9, 3.4, 3.5}; • The length of this array is 4 • int len = myList.length; // len is now 4 • Note, we use myList.length, notmyList.length() • myList.length()would be a method belonging to the array myList. But there is no such method. myList.length is a variable belonging to the array that tells you the number of elements for which that array was created. • Note also, we did not use the keyword new in this form!
Initialization • When we create an array, each element is given a default value • For numbers, this is 0 (or 0.0) • For characters it is the null character • For objects, it is the null reference (more on objects later) • For booleans, it is false
Doing things to elements in an array • All elements are of the same kind (int, double, Circle, etc) • The length of the array is known • To do anything to each element, we invariably use a for-loop // print out each element for(int i=0; i<myList.length; i++) { System.out.print(myList[i] + " "); }
Example to study: Liang, p. 168-169 • This example asks the user to input the number of students • It then creates an array, with one element per student • The user then enters an appropriate number of scores (one for-loop) • It then iteratesover these scores (the array) and prints out each as a letter grade
Common errors with Arrays There is no spacebefore square brackets: int[] scores; scores = new int[6]; There is always a space (or a semicolon) after square brackets (type given, no number) means ‘declare an array variable that will hold things of this type’ int[] (type given, number given) means ‘create new space in memory for an array of this number of elements of this type’ int[6] scores[3] (variable name given not type; number given) means ‘return the element in box indexed by number from array pointed to by variable name’
Off-by-one errors • The first index in an array is always 0 • The index of the last element is array.length - 1 • What happens if we try to access an element which is not in the range [0..length-1]? • This common error generates an ArrayIndexOutOfBoundsException • This is not caught by the compiler! An exception is a run-time error • Trying to access myList[4] when myList is of length 4 is called an off-by-one error........................very common!!!
8 1 19 12 0 5 7 11 15 9 3 1 0 1 1 3 5 7 8 9 11 12 15 19 Searching for an element I: Linear Search Q: does the number 5 occur in the following array? Q: what about this one?
Linear Search implemented: Liang p 190 // method to find a key in a list public static int linearSearch(int key, int[] list) { for(int i=0; i<list.length; i++) { if(key == list[i]) return i; } return -1; // return –1 if the key is not found // otherwise return key’s location }
Analysis of Linear Search • Linear search is not very efficient • Imagine looking for a telephone number in an unsorted telephone book • If an array of size X takes p seconds to search exhaustively, how long will an array of size 2X take to search? • Execution of Linear Search is proportional to the length of the array to be searched • Its complexityis of Order n, where n is the length of the array • Linear Search is an O(n) algorithm