Week 7 Arrays and ArrayLists PDF
Document Details
Uploaded by Deleted User
2014
Tags
Summary
This document provides lecture notes on arrays and ArrayLists in Java. It covers topics like declaring arrays, copying arrays, using arrays in methods, common array errors, the enhanced for loop, two-dimensional arrays, the ArrayList class, wrapper classes, and common array algorithms.
Full Transcript
COMP2202 Fundamentals of Object Oriented Programming Chapter 6 – Arrays and Array Listss 1 Lecture Goals To collect elements using arrays and array lists To use the enhanced for loop for traversing arrays and array lists T...
COMP2202 Fundamentals of Object Oriented Programming Chapter 6 – Arrays and Array Listss 1 Lecture Goals To collect elements using arrays and array lists To use the enhanced for loop for traversing arrays and array lists To learn common algorithms for processing arrays and array lists To work with two-dimensional arrays Copyright © 2014 by John Wiley & Sons. All rights 2 reserved. Outline 1. Declaring arrays 2. Copying arrays 3. Using arrays in methods 4. Common arrays errors 5. The enhanced for loop 6. 2D arrays 7. The ArrayLists class 8. Wrapper classes 9. Common array algorithms Copyright © 2014 by John Wiley & Sons. All rights 3 reserved. Arrays An array stores a sequence of values of the same type. The following statement creates an array capable of storing 10 double values. double[] values = new double; An array cannot change size at run time. An array index ranges from zero to the size of the array -1. The first element is values, and the last element is values The following statement sets the array element at index 4 to 35: values = 35 Copyright © 2014 by John Wiley & Sons. All rights 4 reserved. Array References By default, each number in the array is set to 0. What are the default values of Boolean, char and String arrays? The new operator constructs the array and returns a reference specifying the location of the array in memory When you copy an array variable into another, both variables refer to the same array int[] scores = {10, 9, 7, 4, 5}; int[] values = scores; // Copying array reference Copyright © 2014 by John Wiley & Sons. All rights 5 reserved. Array Initialization Lists Arrays can be created using initialization list double[] moreValues = {32, 54, 67.5, 29, 35, 80, 115, 44.5, 100, 65}; This will specify the initial values when you create the array The size of the array equals the number of elements in the list. Copyright © 2014 by John Wiley & Sons. All rights 6 reserved. Syntax: Declaring Arrays Copyright © 2014 by John Wiley & Sons. All rights 7 reserved. Declaring Arrays Copyright © 2014 by John Wiley & Sons. All rights 8 reserved. Copying an Array Copying an array variable yields a second reference to the same array: double[] values = new double;... // Fill array double[] prices = values; To make a true copy of an array, call the Arrays.copyOf method: double[] values = new double; double[] prices = Arrays.copyOf(values, values.length); How to copy arrays in Java? There are some other available methods such as: -System.arraycopy() -clone method See here for more details Copyright © 2014 by John Wiley & Sons. All rights 9 reserved. Copying an Array Figure 3 Copying an Array Reference versus Copying an Array Copyright © 2014 by John Wiley & Sons. All rights 10 reserved. Using Arrays with Methods Arrays can occur as method arguments and return values. An array as a method argument public void addScores(int[] values) { for (int i = 0; i < values.length; i++) { totalScore = totalScore + values[i]; } } To call this method int[] scores = { 10, 9, 7, 10 }; fred.addScores(scores); //get total scores of a student Fred A method with an array return value public int[] getScores() For example: a student class can have “getScores” method to return an array with all student’s scores Copyright © 2014 by John Wiley & Sons. All rights 11 reserved. Common Errors Copyright © 2014 by John Wiley & Sons. All rights 12 reserved. Common Errors Copyright © 2014 by John Wiley & Sons. All rights 13 reserved. The Enhanced for Loop You can use the enhanced for loop to visit all array elements Totaling array elements with the enhanced for loop double[] values =...; double total = 0; for (double element : values){ total = total + element; } The loop body is executed for each element in the array values. Read the loop as “for each element in values”. Traditional alternative, using array index: for (int i = 0; i < values.length; i++) { double element = values[i]; total = total + element; } Copyright © 2014 by John Wiley & Sons. All rights 14 reserved. The Enhanced for Loop Not suitable for all array algorithms. Does not allow you to modify the contents of an array. Why? The following loop does not fill an array with zeros: for (double element : values) { element = 0; // ERROR: this assignment does not modify // array elements } Use a basic for loop instead: for (int i = 0; i < values.length; i++) { values[i] = 0; // OK } Copyright © 2014 by John Wiley & Sons. All rights 15 reserved. Syntax: The Enhanced for Loop Use the enhanced for loop if you do not need the index values in the loop body. The enhanced for loop is a convenient mechanism for traversing all elements in a collection. Copyright © 2014 by John Wiley & Sons. All rights 16 reserved. Two-Dimensional Array An arrangement consisting of rows and columns of values, also called a matrix. You cannot change the size of a two-dimensional array once it has been declared. Copyright © 2014 by John Wiley & Sons. All rights 17 reserved. Two-Dimensional Arrays Example: medal counts of the figure skating competitions at the 2010 Winter Olympics. Figure 12 Figure Skating Medal counts Copyright © 2014 by John Wiley & Sons. All rights 18 reserved. Two-Dimensional Arrays To create a 2D array to hold medal counts: Create an array using: int[][] counts = new int and then fill it. OR Create an array using initialization list: int[][] counts = { { 1, 0, 1 },{ 1, 1, 0 },{ 0, 0, 1 }, { 1, 0, 0 },{ 0, 1, 1 },{ 0, 1, 1 }, { 1, 1, 0 } }; Copyright © 2014 by John Wiley & Sons. All rights 19 reserved. Accessing Elements Access by using two index values, array[i][j] int number= counts; Use nested loops to access all elements in a two- dimensional array. Example: print all the elements of the counts array for (int i = 0; i < ROWS; i++) { // Process the ith row for (int j = 0; j < COLS; j++) { // Process the jth column in the ith row System.out.printf("%8d", counts[i][j]); } System.out.println(); // Start a new line at the end of the row } How can you modify this code to print the average value of array counts? Copyright © 2014 by John Wiley & Sons. All rights 20 reserved. Accessing Elements Number of rows: counts.length Number of columns: counts.length Example: print all the elements of the counts array for (int i = 0; i < counts.length; i++) { for (int j = 0; j < counts.length; j++) { System.out.printf("%8d", counts[i][j]); } System.out.println(); } Copyright © 2014 by John Wiley & Sons. All rights 21 reserved. Array Lists (similar to list in python) An array list stores a sequence of values whose size can change. An array list can grow and shrink as needed. ArrayList class supplies methods for many common tasks, such as inserting and removing elements. To declare an array list of strings ArrayList names = new ArrayList(); Angle brakets denote a type parameter Replace String with other class to get an array list of that class ArrayList is a generic class from the java.util package Copyright © 2014 by John Wiley & Sons. All rights 22 reserved. Syntax: Declaring ArrayLists Copyright © 2014 by John Wiley & Sons. All rights 23 reserved. Declaring and Using Array Lists When ArrayList is first constructed, it has size 0 Use the add method to add an object to the end of the array list: names.add("Emily"); // Now names has size 1 names.add("Bob"); // Now names has size 2 names.add("Cindy"); // names has size 3 The size method gives the current size of the array list. The last valid index is names.size() - 1 ArrayList index starts at 0 Figure 14 Adding an Array List Copyright © 2014 by John WileyElement with add & Sons. All rights 24 reserved. Declaring and Using Array Lists To obtain array list element, use the get method: String name = names.get(2); // Gets the third element To set an array list element to a new value, use the set method: names.set(2, "Carolyn"); //overwrite element value in index 2 To add a new element at a given position use the add method. What happen to the element at that position? names.add(1, "Ann"); The remove method, removes the element at a given position. What happen to the elements after the removed element? names.remove(1); To print an array list: System.out.println(names); // Prints [Emily, Bob, Carolyn] Copyright © 2014 by John Wiley & Sons. All rights 25 reserved. Declaring and Using Array Lists Figure 15 Adding and Removing Elements in the Middle of an Array List Copyright © 2014 by John Wiley & Sons. All rights 26 reserved. Using the Enhanced for Loop with Array Lists You can use the enhanced for loop to visit all the elements of an array list ArrayList names =new ArrayList(); for (String name : names) { System.out.println(name); } This is equivalent to: for (int i = 0; i < names.size(); i++) { String name = names.get(i); System.out.println(name); } Copyright © 2014 by John Wiley & Sons. All rights 27 reserved. Copying Array Lists Copying an array list reference yields two references to the same array list. After the code below is executed Both names and friends reference the same array list to which the string "Harry" was added. ArrayList friends = names; friends.add("Harry"); To make a copy of an array list, construct the copy and pass the original list into the constructor: ArrayList names =new ArrayList(); ArrayList newNames = new ArrayList(names); 28 Working With Array Lists Copyright © 2014 by John Wiley & Sons. All rights 29 reserved. Wrapper Classes You cannot directly insert primitive type values into ArrayLists. ArrayList // Compilation ERROR as double is primitive type A number must be placed in a wrapper class to be stored in ArrayList ArrayList // Double is a wrapper class representing a double value Automatic conversion between primitive types and the corresponding wrapper classes is called “auto-boxing” and “unboxing”: Double wrapper = 29.95; double x = wrapper; Copyright © 2014 by John Wiley & Sons. All rights 30 reserved. Array Lists Common Algorithms Code to read inputs and add them to an ArrayList: ArrayList inputs = new ArrayList(); while (in.hasNextDouble()) { inputs.add(in.nextDouble()); } Swapping Elements ArrayList age = new ArrayList(); age.add(20); age.add(25); int temp=age.get(0); age.set(0,age.get(1)); age.set(1, temp); System.out.println("arraylists= "+age); Find the largest element in an array list: double largest = values.get(0); for (int i = 1; i < values.size(); i++) { if (values.get(i) > largest) { largest = values.get(i); } } Copyright © 2014 by John Wiley & Sons. All rights 31 reserved. Array Lists Common Algorithms: Linear Search To find the position of an element, visit all elements until you have found a match or you have come to the end of the array Example: Find the first element that is equal to 100 ArrayList age = new ArrayList(); age.add(230); age.add(25); age.add(100); age.add(250); System.out.println("arraylists= "+age); int pos = 0; boolean found = false; while (pos < age.size() && !found) { if (age.get(pos) == 100) { found = true; } else { pos++; } } if (found) { System.out.println("Found at position: " + pos); } else { System.out.println("Not found"); } This algorithm is called a linear search. A linear search inspects elements in sequence until a match is found Copyright © 2014 by John Wiley & Sons. All rights 32 reserved. Two-Dimensional ArrayLists An ArrayList does not have dimensions like Arrays. Have nested ArrayLists which are also called ‘2D ArrayLists’ or ‘ArrayList of ArrayLists’. The simple idea behind these nested ArrayLists is that given an ArrayList, each element of this ArrayList is another ArrayList. Copyright © 2014 by John Wiley & Sons. All rights 33 reserved. Choosing Between Array Lists and Arrays For most programming tasks, array lists are easier to use than arrays Array lists can grow and shrink. Arrays have a nicer syntax. Recommendations If the size of a collection never changes, use an array. If you collect a long sequence of primitive type values and you are concerned about efficiency, use an array. Otherwise, use an array list. Copyright © 2014 by John Wiley & Sons. All rights 34 reserved. Choosing Between Array Lists and Arrays Copyright © 2014 by John Wiley & Sons. All rights 35 reserved.