1 / 127

Chapter 7 Arrays and Array Lists

Chapter 7 Arrays and Array Lists. Assignment:. Read lessons 7.1 thru 7.8, take notes, and complete the self-check questions in your notebook Written exercises: R7.1, 7.3, 7.4,7.6 – 7.7 R7.11, 7.12, 7.16 – 7.19 -- Due December 9, 2013

mare
Télécharger la présentation

Chapter 7 Arrays and Array Lists

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. Chapter 7Arrays and Array Lists

  2. Assignment: • Read lessons 7.1 thru 7.8, take notes, and complete the self-check questions in your notebook • Written exercises: R7.1, 7.3, 7.4,7.6 – 7.7 R7.11, 7.12, 7.16 – 7.19 -- Due December 9, 2013 • Programming exercises P7.2 – 7.6, 7.9, 7.10, 7.13 -- Due December 17, 2013 • For 7.2 – 7.6 You may write one long program that includes each modification to your Purse Class. Comment each method as 7.2, or 7.3, or 7.4 …etc. • Work with one other person and submit one final copy of the all programs to the completed works folder. • FunNumber2 exercises – due December 20, 2013

  3. Chapter Goals • To become familiar with using arrays and array lists • To learn about wrapper classes, auto-boxing and the generalized forloop • To study common array algorithms Continued…

  4. Chapter Goals • To learn how to use two-dimensional arrays • To understand when to choose array lists and arrays in your programs • To implement partially filled arrays

  5. Arrays • An array is a fixed-length sequence of values of the same type. • You access array elements with an integer index, using the notation a[i]. • The number of elements an array can hold is accessed by using the length field of the array:a.length. (notice no () after length, because it is a public final field) • Arrays can hold primitive values or objects.

  6. Arrays • Construct array: • Store in variable of type double[ ] • Find Length of an array double[] data = new double[10]; new double[10] System.out.println (data.length); Continued…

  7. Arrays • Arrays are often partially filled and you need to remember the number of elements that you actually placed in the array.

  8. Arrays • Note that length is the number of elements the array can hold….not the number of positions filled. int[] a = new int[5]; a[0] = 78; a[1] = 89; for (int x = 0; x < a.length ; x++) { System.out.print("\t"+ a[x] + "\t"); } prints: 78 89 0 0 0

  9. Arrays • When array is created, all values are initialized depending on array type: • Numbers: 0 • Boolean: false • Object References: null

  10. Arrays Figure 1:An Array Reference and an Array

  11. Arrays • Use [ ] to access an element data[2] = 29.95; Figure 2:Storing a Value in an Array

  12. Arrays • Using the value stored: • Get array length as data.length. (Not a method!) • Index values range from 0 to(length - 1) System.out.println("The value of this data item is " + data[4]); Array Name Continued…

  13. Arrays • Arrays are often partially filled and you need to remember the number of elements that you actually placed in the array. // filling array from input import java.util.Scaner; … scanner in = new Scanner(System.in); int count = 0; boolean done = false; intmaxCount = 10; int[] arr = new int[maxCount]; while(count < maxCount && !done) { System.out.println("Enter integer (-1 to quit.): "); int a = in.nextInt(); if (a != -1) { arr[count] = a; count++; } else done = true; } size = count; // Remember number of filled // elements } }

  14. Arrays • Arrays are often partially filled and you need to remember the number of elements that you actually placed in the array and carry it around with you! public static void listForward(int[] tList, intnum) { for (int x = 0; x < num; x++) { System.out.print("\t"+ tList[x] + "\t"); } System.out.println(); }

  15. Arrays • Accessing a nonexistent element results in a bounds error • Limitation: Arrays have fixed length double[] data = new double[10];data[10] = 29.95; // ERROR

  16. Self Check • What elements does the data array contain after the following statements? Ans: 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, but not 100 double[] data = new double[10];for (int i = 0; i < data.length; i++) data[i] = i * i;

  17. Self Check • What do the following program segments print? Or, if there is an error, describe the error and specify whether it is detected at compile-time or at run-time. • 0 • a runtime error: array index out of bounds 3. a compile-time error: c is not initialized • double[] a = new double[10]; System.out.println(a[0]); • double[] b = new double[10]; System.out.println(b[10]); • double[] c; System.out.println(c[0]);

  18. Copying Arrays: Copying Array References • Copying an array variable yields a second reference to the same array double[] data = new double[10];// fill array . . .double[] prices = data; Continued…

  19. Copying Arrays: Copying Array References Figure 7:Two References to the Same Array

  20. Copying Arrays: Cloning Arrays • Use clone to make true copy double[] prices = (double[]) data.clone(); Need to cast as a (double) since cloned type is an Object Continued…

  21. Copying Arrays: Cloning Arrays Figure 8:Cloning an Array

  22. Copying Arrays: Copying Array Elements System.arraycopy(from, fromStart, to, toStart, count); How many elements to copy From Array Name To Array Name Continued…

  23. Copying Arrays: Copying Array Elements Figure 9:The System.arraycopy Method

  24. Arrays • Now, what if you run out of room? • You must allocate a larger array and copy the elements from the original array to the larger array.

  25. Growing an Array • If the array is full and you need more space, you can grow the array: • Create a new, larger array. • Copy all elements into the new array • Store the reference to the new array in the array variable double[] newData = new double[2 * data.length]; System.arraycopy(data, 0, newData, 0, data.length); data = newData;

  26. Arrays • You must allocate a larger array and copy the elements from the original array to the larger array. data newData free space By setting data = newData the array data now references the copy.

  27. Growing an Array Figure 12:Growing an Array

  28. Sample Code • You must allocate a larger array and copy the elements from the original array to the larger array. int[] copyOfArray = new int[2* arr.length]; for (int i = 0; i < arr.length; i++) { copyOfArray[i] = arr[i]; } arr = copyOfArray;

  29. Simple Array Algorithms: Finding the Maximum or Minimum Steps -- Ex.  Find the largest bank acct balance • Initialize a candidate with the starting element • Compare candidate with remaining elements • Update it if you find a larger or smaller value Continued…

  30. Simple Array Algorithms: Finding the Maximum or Minimum • Example: BankAccountlargestYet = accounts[0];for (inti = 1; i < accounts.length; i++){BankAccount a = accounts[i]; if (a.getBalance() > largestYet.getBalance())largestYet = a;}return largestYet;

  31. Filling an Array using an initializer list: • Instead of: int[] primes = new int[3]; primes[0] = 2; primes[1] = 3; primes[2] = 5; • Use: int[]primes = {2, 3, 5};

  32. Arrays • It is not very convenient to track array sizes and to grow arrays when they run out of space. • If you are collecting objects, use ArrayList. • If you collect numbers, you must make a choice. Which is the least inconvenient? • Using wrapper classes? • Tracking array size?

  33. Dr. Seuss: "Too Many Daves" Did I ever tell you that Mrs. McCaveHad twenty-three sons, and she named them all Dave? Well, she did. And that wasn't a smart thing to do.You see, when she wants one, and calls out "Yoo-Hoo! Come into the house, Dave!" she doesn't get one. All twenty-three Daves of hers come on the run!

  34. "Too Many Daves" This makes things quite difficult at the McCaves'As you can imagine, with so many Daves.And often she wishes that, when they were born,She had named one of them Bodkin Van Horn.And one of them Hoos-Foos. And one of them Snimm. And one of them Hot-Shot. And one Sunny Jim.Another one Putt-Putt. Another one Moon Face.Another one Marvin O'Gravel Balloon Face.And one of them Zanzibar Buck-Buck McFate... But she didn't do it. And now it's too late. http://www.mit.edu/people/dpolicar/writing/poetry/poems/tooManyDaves.html

  35. This is not all that bad….. Come into the house, Dave!" she doesn't get one.All twenty-three Daves of hers come on the run!

  36. ArrayList • It is very common for applications to require us to store a large amount of data. • Array Lists store large amounts of data in a single collection that can be referred to with a single variable.

  37. ArrayList • An ArrayList is a sequence of objects that grows and shrinks as needed. • The ArrayList class is part of the java.util package of the Java standard class library.

  38. ArrayList • Each element in the sequence can be accessed separately. • We can explicitly overwrite an object at a specified position in the sequence, thus changing its value. • We can inspect the object at a specified location in the sequence.

  39. ArrayList • We can add an object into a specified position of the sequence. • We can add an object to the end of the sequence. • We can remove an object from a specified location in the sequence.

  40. ArrayList methods: • boolean add(Object x) // appends x to the end of list; returns true • int size() // returns the number of elements in this list • Object get(int index)// returns the element at the specified position in this list. • Object set(int index, Object x)// replaces the element at index with x// returns the element formerly at the specified position • Iterator iterator() //Returns an iterator over the elements in the arraylist in proper sequence. • ListIteratorlistIterator() //Returns a list iterator over the elements in this arraylist (in proper sequence). Use to traverse through the list – iterators point between two elements in the list.

  41. More ArrayList methods • void add(int index, Object x) // inserts x at position index, sliding elements // at position index and higher to the right // (adds 1 to their indices) and adjusts size • Object remove(int index)// removes element from position index, sliding // subsequent elements to the left (subtracts 1 from their //indices) and adjusts size// returns the element at the specified position in this list.

  42. Array Lists • The ArrayList class is a generic class: ArrayList<T> collects objects of type T: • size method yields number of elements ArrayList<BankAccount> accounts = new ArrayList<BankAccount>();accounts.add(new BankAccount(1001));accounts.add(new BankAccount(1015));accounts.add(new BankAccount(1022));

  43. Retrieving Array List Elements • Use get method • Index starts at 0 • Bounds error if index is out of range BankAccount anAccount = accounts.get(2); // gets the third element of the array list Continued…

  44. Retrieving Array List Elements • Most common bounds error: int i = accounts.size();anAccount = accounts.get(i); // Error// legal index values are 0. . .i-1 Since positions start at zero

  45. Adding Elements • set overwrites an existing value • add adds a new value before the index BankAccount anAccount = new BankAccount(1729);accounts.set(2, anAccount); accounts.add(i, a) Continued…

  46. Adding Elements Figure 3:Adding an Element in the Middle of an Array List

  47. Removing Elements • remove removes an element at an index Accounts.remove(i) Continued…

  48. Removing Elements Figure 4:Removing an Element in the Middle of an Array List

  49. File: ArrayListTester.java - p294-296 01:import java.util.ArrayList; 02: 03: /** 04: This program tests the ArrayList class. 05: */ 06:public class ArrayListTester 07:{ 08:public static void main(String[] args) 09: { 10: ArrayList<BankAccount> accounts 11: = new ArrayList<BankAccount>(); 12: accounts.add(new BankAccount(1001)); 13: accounts.add(new BankAccount(1015)); 14: accounts.add(new BankAccount(1729)); 15: accounts.add(1, new BankAccount(1008)); 16: accounts.remove(0); Continued…

  50. File: ArrayListTester.java 17: 18: System.out.println("size=" + accounts.size()); 19: BankAccount first = accounts.get(0); 20: System.out.println("first account number=" 21: + first.getAccountNumber()); 22: BankAccount last = accounts.get(accounts.size() - 1); 23: System.out.println("last account number=" 24: + last.getAccountNumber()); 25: } 26:} Output size=3first account number=1008last account number=1729

More Related