Chapter 7 Arrays and Array Lists

Slides:



Advertisements
Similar presentations
1 Various Methods of Populating Arrays Randomly generated integers.
Advertisements

Arrays and ArrayLists Ananda Gunawardena. Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. It is common to use two nested loops when filling or searching: for.
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Chapter 7: Arrays and Array Lists. To become familiar with using arrays and array lists To learn about wrapper classes, auto-boxing and the generalized.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Seven: Arrays and Array Lists.
Chapter 13 ARRAY LISTS AND ARRAYS. CHAPTER GOALS To become familiar with using array lists to collect objects To learn about common array algorithms To.
Chapter 7 Arrays and Array Lists. Chapter Goals To become familiar with using arrays and array lists To learn about wrapper classes, auto-boxing and the.
Chapter 13 ARRAY LISTS AND ARRAYS CHAPTER GOALS –To become familiar with using array lists to collect objects –To learn about common array algorithms –To.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Arrays.
Chapter 7 – Arrays.
Computer Science A 10: 20/3. Array Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[]
Chapter 7  Arrays and Array Lists 1 Chapter 7 Arrays and Array Lists.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
Datalogi A 8: 27/10. Array Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[] data.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
1 Array Lists Pat Phillips Craig High School Janesville, Wisconsin 2005.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Java Programming Week 6: Array and ArrayList Chapter 7.
For each primitive type there is a wrapper class for storing values of that type: Double d = new Double(29.95); Wrapper Classes Wrapper objects can be.
Week 9-10 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
1 ArrayList  Array’s are limited because we need to know the size before we use them.  An ArrayList is an extension of an array that grows and shrinks.
AP CS Workshop ArrayList It is very common for applications to require us to store a large amount of data. Array lists store large amounts of data.
ARRAYLIST Collections of Data. ArrayLists Array lists can grow and shrink as needed ArrayList is a generic class (similar to C++ template) ArrayList has.
1 Dr. Seuss again: "Too Many Daves"  Did I ever tell you that Mrs. McCave Had twenty-three sons, and she named them all Dave?  Well, she did. And that.
ArrayList, Multidimensional Arrays
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
AP Comp Sci A Chapter 12 - Arrays. Ch 12 Goals: Goals: Declare and create arrays Declare and create arrays Access elements in arrays Access elements in.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Chapter 18 Java Collections Framework
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Fall 2006Slides adapted from Java Concepts companion slides1 Arrays and Array Lists Advanced Programming ICOM 4015 Lecture 7 Reading: Java Concepts Chapter.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Arrays. Array: Sequence of values of the same type Construct array: Store in variable of type double[ ] new double[10] double[] data = new double[10];
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 7 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. 1.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
int [] scores = new int [10];
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Data Structures Arrays and Lists Part 2 More List Operations.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Chapter 9 Introduction to Arrays Fundamentals of Java.
LINKED LISTS.
Week 9 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Arrays Chapter 7.
Principles of Computer Science I
Chapter 8 – Arrays and Array Lists
7.6 Common Array Algorithm: Filling
Java Methods ("Chapter %d", 14); Streams and Files A & AB
Introduction to Computer Science and Object-Oriented Programming
int [] scores = new int [10];
int [] scores = new int [10];
Presentation transcript:

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

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

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

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.

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…

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

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

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

Arrays Figure 1: An Array Reference and an Array

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

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…

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; int maxCount = 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

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, int num) { for (int x = 0; x < num ; x++) System.out.print("\t"+ tList[x] + "\t"); } System.out.println();

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

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;

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. 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]);

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…

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

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…

Copying Arrays: Cloning Arrays Figure 8: Cloning an Array

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

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

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.

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;

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.

Growing an Array Figure 12: Growing an Array

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;

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…

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

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};

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?

Dr. Seuss: "Too Many Daves" Did I ever tell you that Mrs. McCave Had 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!

"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

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!

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.

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.

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.

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.

boolean add(Object x) // appends x to the end of list; returns true 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. ListIterator listIterator() //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.

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.

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));

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…

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

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…

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

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

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

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…

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=3 first account number=1008 last account number=1729

Self Check How do you construct an array of 10 strings? An array list of strings? Ans: new String[10]; new ArrayList<String>();

Self Check Continued… What is the content of names after the following statements? Ans: names contains the strings "B" and "C" at positions 0 and 1 ArrayList<String> names = new ArrayList<String>(); names.add("A"); names.add(0, "B"); names.add("C"); names.remove(1);

Wrappers You cannot insert primitive types directly into array lists To treat primitive type values as objects, you must use wrapper classes: ArrayList<Double> data = new ArrayList<Double>(); data.add(29.95); double x = data.get(0); Continued…

Wrappers Figure 5: An Object of a Wrapper Class

Wrappers There are wrapper classes for all eight primitive types

Auto-boxing Auto-boxing: Starting with Java 5.0, conversion between primitive types and the corresponding wrapper classes is automatic. Double d = 29.95; // auto-boxing; same as Double d = new Double(29.95); double x = d; // auto-unboxing; same as double x = d.doubleValue(); Continued…

Auto-boxing Auto-boxing even works inside arithmetic expressions Means: auto-unbox d into a double add 1 auto-box the result into a new Double store a reference to the newly created wrapper object in e Double e = d + 1;

Self Check What is the difference between the types double and Double? Ans: double is one of the eight primitive types. Double is a class type. Suppose data is an ArrayList<Double> of size > 0. How do you increment the element with index 0? Ans: data.set(0, data.get(0) + 1);

The Enhanced for Loop Traverses all elements of a collection: double[] data = . . .; double sum = 0; for (double e : data) // You should read this loop as // "for each e in data" { sum += e; } Continued…

The Enhanced for Loop Traditional alternative: double[] data = . . .; double sum = 0; for (int i = 0; i < data.length; i++) { double e = data[i]; sum += e; }

The Enhanced for Loop Works for ArrayLists too: ArrayList<BankAccount> accounts = . . . ; double sum = 0; for (BankAccount a : accounts) { sum += a.getBalance(); }

The Enhanced for Loop Equivalent to the following ordinary for loop: double sum = 0; for (int i = 0; i < accounts.size(); i++) { BankAccount a = accounts.get(i); sum = sum + a.getBalance(); }

Syntax 7.3: The "for each" Loop  for (Type variable : collection) statement Example:  for (double e : data) sum = sum + e; Purpose: To execute a loop for each element in the collection. In each iteration, the variable is assigned the next element of the collection. Then the statement is executed.

Self Check Write a "for each" loop that prints all elements in the array data Ans: Why is the "for each" loop not an appropriate shortcut for the following ordinary for loop? Ans: The loop writes a value into data[i]. The "for each" loop does not have the index variable i. for (double x : data) System.out.println(x); for (int i = 0; i < data.length; i++) data[i] = i * i;

Simple Array Algorithms: Counting Matches Textbook Page 303-305 Check all elements and count the matches until you reach the end of the array list. public class Bank { public int count(double atLeast) { int matches = 0; for (BankAccount a : accounts) { if (a.getBalance() >= atLeast) matches++; // Found a match } return matches; } . . . private ArrayList<BankAccount> accounts; }

Simple Array Algorithms: Finding a Value Check all elements until you have found a match. public class Bank { public BankAccount find(int accountNumber) for (BankAccount a : accounts) if (a.getAccountNumber() == accountNumber) // Found a match return a; } return null; // No match in the entire array list . . .

Simple Array Algorithms: Finding the Maximum or Minimum Works only if there is at least one element in the array list If list is empty, return null if (accounts.size() == 0) return null; BankAccount largestYet = accounts.get(0); . . .

BankAccount largestYet = accounts.get(0); Initialize a candidate with the starting element Compare candidate with remaining elements Update it if you find a larger or smaller value Example: BankAccount largestYet = accounts.get(0); for (int i = 1; i < accounts.size(); i++) { BankAccount a = accounts.get(i); if (a.getBalance()> largestYet.getBalance()) largestYet = a; } return largestYet;

Two-Dimensional Arrays When constructing a two-dimensional array, you specify how many rows and columns you need: You access elements with an index pair a[i][j] final int ROWS = 3; final int COLUMNS = 3; String[][] board = new String[ROWS][COLUMNS]; board[i][j] = "x";

Traversing Two-Dimensional Arrays It is common to use two nested loops when filling or searching: See File: TicTacToe.java – text pages 307-308 for (int i = 0; i < ROWS; i++) for (int j = 0; j < COLUMNS; j++) board[i][j] = " ";

A Tic-Tac-Toe Board Figure 6: A Tic-Tac-Toe Board

Self Check How do you declare and initialize a 4-by-4 array of integers? ans: int[][] array = new int[4][4]

Regression Testing Save test cases Use saved test cases in subsequent versions A test suite is a set of tests for repeated testing Cycling = bug that is fixed but reappears in later versions Regression testing: repeating previous tests to ensure that known failures of prior versions do not appear in new versions See regression/BankTester.java pp. 319 – 320.

Self Check 7.15 Suppose you modified the code for a method. Why do you want to repeat tests that already passed with the previous version of the code? Answer: It is possible to introduce errors when modifying code.

Self Check 7.16 Suppose a customer of your program finds an error. What action should you take beyond fixing the error? Answer: Add a test case to the test suite that verifies that the error is fixed.

Arrays/ Array lists Applications?

What to do with arrays…. Input Process Output How? What? Where? Get “stuff” into our array Process Do something with the stuff in our array Output Display contents of our array How? What? Where?

Input // filling arrays with consecutive integers for (count = 0;count < 20;count++) { v[count] = count ; } // filling array list with consecutive integers v.add(new Integer(count));

Input String pathname = "..h:\\yourFilename\\Data.txt“; // filling array from file int count = 0; String pathname = "..h:\\yourFilename\\Data.txt“; File file = File(pathname); Scanner input = null; try { input = new Scanner(file); } catch (FileNotFoundException ex) System.out.println("*** Cannot open " + pathname + " ***"); System.exit(1); // quit the program try-catch block – page 508 of textbook

while(count < maxCount && input.hasNextInt()) { int a = input.nextInt(); arr[count] = a; count++; } size = count; //number of filled elements

Input // filling array list from file ArrayList<Integer> arr = new ArrayList<Integer>(); while(input.hasNextInt()) { int a = input.nextInt(); if (input.hasNextInt()) arr.add(a); }

What about filling our 20-element container with random integers from 1 to 100? final int MAXELTS = 20; Random generator = new Random(); int[] a = new int[MAXELTS]; for(int k = 0; k < MAXELTS; k++) { a[k] = generator.nextInt(100) + 1; }

What about filling our 20-element container with random integers from 1 to 100? final int MAXELTS = 20; Random generator = new Random(); int[] a = new int[MAXELTS]; for(int k = 0; k < MAXELTS; k++) { a[k] = generator.nextInt(100) + 1; } How does this change with an ArrayList?

What about filling our 20-element container with random integers from 1 to 100 -- ArrayList? final int MAXELTS = 20; Random generator = new Random(); ArrayList<Integer> a = new ArrayList<Integer>; for (int k = 0; k < MAXELTS; k++) { int num = generator.nextInt(100)+1; a.add(num); }

PROBLEM : Fill a 20-element 'container' with random integers from 1-100 inclusive ensuring that there are no duplicate values in array.

We will look at several possible solutions. PROBLEM : Fill a 20-element 'container' with random integers from 1-100 inclusive ensuring that there are no duplicate values in array. We will look at several possible solutions. You will be asked for others. You will be asked your preference and a justification! Note : solutions are not given in Java code!

Solution 1 : for (int k = 0; k < 20; k++) do 4 8 6 23 * for (int k = 0; k < 20; k++) do Generate random integer(1-100) Check all elements in array that are filled already until random number is not a dupe while (random num is a dupe); Put the non-dupe in array 8

Solution 1 : for (int k = 0; k < 20; k++) do 4 8 6 23 * for (int k = 0; k < 20; k++) do Generate random integer(1-100) Check all elements in array that are filled already until random number is not a dupe while (random num is a dupe); Put the non-dupe in array space efficiency? time efficiency? 8

Solution 1 : for (int k = 0; k < 20; k++) do 4 8 6 23 * for (int k = 0; k < 20; k++) do Generate random integer(1-100) Check all elements in array that are filled already until random number is not a dupe while (random num is a dupe); Put the non-dupe in array space efficiency? OK time efficiency? not very 8

Solution 2: Choose a random number, r Create an additional array, b, with 101 elements (random choices are from 1-100) and fill it with 0s. for (int k = 0; k < 20; k++) do Choose a random number, r while b[r] = 0 Put r in your array Put 1 in b[r] to mark it “taken”

Solution 2 : a picture b a 1 4 8 Choose a random number, r 8 b[1] b[2] b[3] b[4] 1 b[5] b[6] b[7] b[8] b[9] b[10] b[11] 4 8 for (int k=0; k < 20; k++) do Choose a random number, r 8 while b[r] = 0 Put r in your array Put 1 in b[r] to mark it “taken”

Solution 3: Create an additional array, b, with 101 elements (random choices are from 1-100) and fill it with indices of b (b[1] = 1, b[5]= 5). Set n = 100; for (int k=0;k<20;k++) Choose a random number, r, in the range [1, n] Put r in your array b[n] replaces b[r] Decrement n

Solution 3 : a picture A 4 1 2 3 4100 5 6 7 8 9 10 11 n= 100 b[0] b[1] 1 b[2] 2 b[3] 3 b[4] 4100 b[5] 5 b[6] 6 b[7] 7 b[8] 8 b[9] 9 b[10] 10 b[11] 11 n= 100 for (int k=0; k < 20; k++) Choose a random number, r, in the range [1, n] 4 Put b[r] in your array b[n] replaces b[r] Decrement n n = 99

Solution 4: Choose a random number, r, in the range [0, 99] Create an array, b, with 100 elements (random choices are from 1-100) and fill it with (index + 1) (b[0] = 1, b[4]= 5). for (int k=0;k< 20;k++) Choose a random number, r, in the range [0, 99] Swap b[k] with b[r]

Solution 4 : a picture b[0] 1 b[1] 2 b[2] 3 b[3] 4 b[4] 5 b[5] 6 b[6] 7 b[7] 8 b[8] 9 b[9] 10 b[10] 11 b[11] 12 5 for (int k=0; k < 20; k++) Choose a random number, r, in the range [0, 99] 4 Swap b[r] with b[k] copy the first 20 elements of b to an array of size 20 and assign b to this reference. to swap: int temp = a[i]; a[i] = a[j]; a[j] = temp; 1

Solution 5 : Assign to each of the first 100 elements of an ArrayList, b, the value of index + 1. Create a new empty ArrayList (or 20-element array), a. for(int x = 1; x < = 20; x++) Choose a random integer in the range [0, b.size()] Remove this element from b and add it to a.

Solution 5 : A picture Assign to each of the first 100 elements of an ArrayList, b, the value of index + 1. Create a new empty ArrayList, a. for(int x = 1; x < = 20; x++) Choose a random integer in the range [0, b.size()] Remove this element from b and add it to a. 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 9 10 1 3 4 5 6 7 9 10 8 2

Other solutions ???

You should be able to Give advantages and disadvantages of each solution Discuss time and space considerations Commit to and defend one of the solutions

Now………. Our array is filled Let’s process……. (by some obscure method) Find the sum. Find the mean. Find the largest/smallest value. Many other things we can do….

Find the largest value in the array/array list int large = a[0]; for(int k = 0; k < a.length; k++) { if (a[k] > large) large = a[k]; } System.out.println("The largest value is: " + large);

Find the largest value in the array/array list ArrayList<Integer>nums = new ArrayList<Integer>(); int large = nums.get(0); for (int i = 0; i < nums.size(); i++) { int tempLarge = nums.get(i); if(tempLarge.compareTo(large) > 0) large = tempLarge; } compareTo returns a value < 0 if tempLarge is less than large returns a value = 0 if tempLarge is equal to large returns a value > 0 if tempLarge is greater than large

PROBLEM/Example code: Report the number that has the longest sequence of consecutive repeated values in an array/array list. If the array contains  3 5 6 8 3 0 0 4 4 4 2 3 3 3 3 3 9 9 9, the number 3 should be reported) public static int longSequence(int[] v) { int seqIndex = 0; // holds index of number in seq int longSeq= 1; // holds longest sequence so far int count = 1; // current sequence length

3 5 6 8 3 0 0 4 4 4 2 3 3 3 3 3 9 9 9 for ( int k = 1; k < v.length; k++ ) { if ( v[k] == v[k-1] ) count++; //current seq length if ( count > longSeq ) longSeq = count; seqIndex = k; } else count = 1; return v[seqIndex]; // ANSWER k = 1; int seqIndex = 0; int longSeq = 1; int count = 1

How else can we process ??? Find the largest number in array Determine if there are duplicates Find the mean (how?) Find the median (how?) Find the mode (how?) Sort the array (more on this later)

Declaring multiple arrays int[] a, b; // Declares two arrays – uninitialized now a = new int[10]; b = new int [10]; =============================== int a[], b; // Declares one array and one int int a, b[]; // Declares one array and one int

Initializer Lists int[] arr = {10, 20, 30, 40, 50, 60, 70, 80}; System.out.println("Printing arr"); for (int i = 0; i < arr.length; i++) // arr's length is 8 { System.out.print(arr[i] + " "); } // 10 20 30 40 50 60 70 80

A word about efficiency Problem: Insert an element into an array (that is not full). Insert it as the first element. Insert it as the last element. Insert it in the middle. Delete an element from an array. Delete the first element. Delete the last element. Delete a middle element.

A word about efficiency (using “big-Oh” notation) Problem: Insert an element into an array (that is not full). Insert it as the first element. O(n) Insert it as the last element. O(1) Insert it in the middle. O(n) Delete an element from an array. Delete the first element. O(n) Delete the last element. O(1) Delete a middle element. O(n)

A word about efficiency Problem: Insert it as the first element. O(n)

A word about efficiency Problem: Insert it as the first element. O(n) Will this work? for (int i = 1; i < arrayName.length; i++) arrayName[i] = arrayName[i - 1]; arrayName[0] = newValue; newValue = 90; 12 13 14 88 45 32 17 __ __ __

A word about efficiency Problem: Insert it as the first element. O(n) Will this work? for (int i = 1; i < arrayName.length; i++) arrayName[i] = arrayName[i - 1]; WRONG arrayName[0] = newValue; newValue = 90; 12 13 14 88 45 32 17 __ __ __

A word about efficiency Problem: Insert it as the first element. O(n) Will this work? for (int i = arrayName.length ; i > 0; i--) arrayName[i] = arrayName[i - 1]; arrayName[0] = newValue; newValue = 90; 12 13 14 88 45 32 17 __ __ __

A word about efficiency Problem: Insert it as the first element. O(n) Will this work? for (int i = arrayName.length - 1; i > 0; i--) arrayName[i] = arrayName[i - 1]; CORRECT arrayName[0] = newValue; newValue = 90; 12 13 14 88 45 32 17 __ __ __

A word about efficiency Problem: What about deleting an element? Algorithm? What about number of elements in the array? 12 13 14 88 45 32 17 __ __ __

equals Using equals with array lists will use the default Object equals and will compare references not contents -- . equals returns true if two ArrayList references are the same, false otherwise. When you use equals with arrays, you are also comparing references. array1.equals(array2) is asking if array1 and array2 reference the same array.

Arrays and Array Lists as Parameters to Methods: A method cannot change the size of an array parameter. Why not? A method can change the length of an array list that is passed as a parameter. Why? You can change the contents of the array/array list but you cannot change the reference.

Make Parallel Arrays into Arrays of Objects // Don't do this int[] accountNumbers; double[] balances; Figure 13: Avoid Parallel Arrays

Make Parallel Arrays into Arrays of Objects Avoid parallel arrays by changing them into arrays of objects: BankAccount[] = accounts; Figure 14: Reorganizing Parallel Arrays into Arrays of Objects

java.io How do I read an int from a file? BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter ByteArrayInputStream ByteArrayOutputStream CharArrayReader CharArrayWriter DataInputStream DataOutputStream File FileDescriptor FileInputStream FileOutputStream FilePermission FileReader FileWriter FilterInputStream FilterOutputStream FilterReader FilterWriter InputStream InputStreamReader LineNumberInputStream LineNumberReader ObjectInputStream ObjectInputStream.GetField ObjectOutputStream ObjectOutputStream.PutField ObjectStreamClass ObjectStreamField OutputStream OutputStreamWriter PipedInputStream PipedOutputStream PipedReader PipedWriter PrintStream PrintWriter PushbackInputStream PushbackReader RandomAccessFile Reader SequenceInputStream SerializablePermission StreamTokenizer StringBufferInputStream StringReader StringWriter Writer How do I read an int from a file? Java IO is not for the faint at heart. It looks like Java developers went all out to confuse programmers. That’s why programmers are such well-paid specialists.

java.io (cont’d) Uses four hierarchies of classes rooted at Reader, Writer, InputStream, OutputStream. InputStream/OutputStream hierarchies deal with bytes. Reader/Writer hierarchies deal with chars. Has a special stand-alone class RandomAccessFile. The Scanner class has been added to java.util in Java 5 to facilitate reading numbers and words. The developer of the RandomAccessFile class probably was not a “team player,” as they say in the industry. Or this part of the project was assigned to a different group. Scanner is an afterthought (Java 5). Scanner got rid of checked exceptions (except in the constructor). It still won’t let you read one character.

java.io.File The File class represents a file (or folder) in the file directory system. Methods: String getName() // Returns the name of the file or directory String getAbsolutePath() // Returns the absolute pathname string long length() // Returns the length of the file boolean isDirectory() //tests if file is a directory File[ ] listFiles() // Returns an array of abstract pathnames denoting //the files in the directory String pathname = "../Data/words.txt“; File file = new File(pathname); A File object does not have to be associated with an open file. In fact, it can represent a directory entry for a file that does not exist yet.

Reading from a Text File String pathname = "words.txt"; File file = new File(pathname); Scanner input = null; try { input = new Scanner(file); } catch (FileNotFoundException ex) System.out.println("*** Cannot open " + pathname + " ***"); System.exit(1); // quit the program Tries to open the file You have used the same Scanner class to read from the keyboard.

Scanner Methods boolean hasNextLine() String nextLine() boolean hasNextInt() int nextInt() boolean hasNextDouble() double nextDouble() void close() Reads one word You can check whether a particular token (an int, a word) exists in the stream, then read it.

Writing to a Text File String pathname = "output.txt"; File file = new File(pathname); PrintWriter output = null; try { output = new PrintWriter(file); } catch (FileNotFoundException ex) System.out.println("Cannot create " + pathname); System.exit(1); // quit the program output.println(...); output.printf(...); output.close(); Once a PrintWriter has been created, you can write to it using print, println, and printf methods, the same way you write to the console screen. Required to flush the output buffer

Summary We can create arrays/ array lists We can fill them We can process them We can output their contents Which do we use….. Array lists? Arrays?

Programming Exercises Continued… Fun Number Lab2 – FunNumber2.java on s:\drive Read in FNUM1, FNUM2, and FNUM3 lists from the s:\ drive in Assignments/AP Java/data(See chapter 11.1 for file reading using Scanner class) Find: Number of elements Maximum Minimum Mode Median Mean