Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays Horstmann, Chapter 8. arrays Fintan 012345 Array of chars For example, a String variable contains an array of characters: An array is a data structure.

Similar presentations


Presentation on theme: "Arrays Horstmann, Chapter 8. arrays Fintan 012345 Array of chars For example, a String variable contains an array of characters: An array is a data structure."— Presentation transcript:

1 Arrays Horstmann, Chapter 8

2 arrays Fintan 012345 Array of chars For example, a String variable contains an array of characters: An array is a data structure which stores several elements All elements are the same type (e.g. int, double, char, String....) String myName = “Fintan”; public static int length(){…} public static boolean equal(String x){…} creates a box like this in the computer’s memory: Each box’s number is called its index These are some of the methods that Strings have (that the String class has) … public static char charAt(int i){…} Array of char s: each char in a numbered box. myName

3 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......................

4 Example: keeping track of class scores next score: 87 next score: 62 next score: 45 next score: 64 next score: 30 next score: 88 We will store these numbers in an array of int s called scores 876245308864 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 scores 012345

5 Declaring and creating an array int[] scores; // declaration scores = new int[6]; // creation int[] means “an 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 ( int s). int[] scores; means scores is the name for this array of integers. new int[6] means “set aside new memory space for an array of six int s”. 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.

6 Declaring and creating in one go scores // both together int[] scores = new int[6]; 000000 This sets aside memory space for an array of six int s, 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: 012345

7 Indexing into an array To refer to elements in an array, we use the array name and the index of the element we want. The first element is scores[0]. Since we created space for 6 elements in the scores array, the last element is scores[5]. // 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); } scores[0] = 87; scores[1] = 62; // and so on 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.

8 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, not myList.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!

9 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

10 Doing things to elements in an array All elements are of the same kind (int, double, BankAccount, objects, Ball objects 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] + " "); }

11 Common errors with Arrays There is no space before square brackets: There is always a space (or a semicolon) after square brackets int[] scores; scores = new int[6]; int[] (type given, no number) means ‘declare an array variable that will hold things of this type’ int[6] (type given, number given) means ‘create new space in memory for an array of this number of elements of this type’ 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’

12 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!!!

13 Objects in arrays Arrays don’t just contain integers. We can create arrays containing BankAccount objects, Ball objects, Strings, etc. When we want to store multiple pieces of information about the items in our array, using Objects is particularly suitable. For example, a Bank might want to have an array (a list) of all the accounts it holds. Each account should hold a customers name and the balance of their account. We first define a bankAccount class, and then each time we want to add a customer’s account to our list (our array) we create a new object from that class and add it to the next empty cell in our array.

14 class BankAccount{ private double balance; private String name; public void deposit(double value) { balance = balance + value; } public void withdraw(double withdrawAmount) { balance = balance - withdrawAmount; } public double getBalance(){ return balance; } public double getName(){ return name; } public BankAccount(String customerName) { name = customerName; balance = 0; } public BankAccount(String customerName, double deposit) { name = customerName; balance = deposit; } } Here’s a simplified version of the BankAccount class. Every object from this class will hold a customer’s name and the balance in their account.

15 class BankAccountTester{ private BankAccount[] accountArray= new BankAccount[10]; public static void main(String[] args) { for(int x = 0; x < accountArray.length; x++){ String n; n= JOptionPane.showInputDialog(null,” customer name? ”); String dString; dString= JOptionPane.showInputDialog(null,” deposit ?”); double d = Double.ParseDouble(dString); accountArray[x] = new BankAccount(n,d); } for(int x = 0; x < accountArray.length; x++){ System.out.println(accountArray[x].getName()+ “ ” + accountArray[x].getBalance() ); } System.exit(0); } Second loop goes through the array, printing out the information on each bankaccount object. First loop populates the array, putting a new BankAccount object in each box in the array.

16 Searching for an element: Linear Search 7111593181191205 Q: does the number 5 occur in the following array? 0113578911121519 Q: what about this one?

17 Linear Search in a method // 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 }


Download ppt "Arrays Horstmann, Chapter 8. arrays Fintan 012345 Array of chars For example, a String variable contains an array of characters: An array is a data structure."

Similar presentations


Ads by Google