+ All Categories
Home > Documents > Chapter 7 Arrays and Array Lists

Chapter 7 Arrays and Array Lists

Date post: 23-Feb-2016
Category:
Upload: mare
View: 80 times
Download: 0 times
Share this document with a friend
Description:
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 - PowerPoint PPT Presentation
127
Chapter 7 Arrays and Array Lists
Transcript
Page 1: Chapter 7 Arrays and Array Lists

Chapter 7

Arrays and Array Lists

Page 2: 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

Page 3: 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 generalized for loop

• To study common array algorithms

Continued…

Page 4: Chapter 7 Arrays and Array Lists

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

Page 5: Chapter 7 Arrays and Array Lists

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.

Page 6: Chapter 7 Arrays and Array Lists

Arrays

• Construct array:

• Store in variable of type double[ ]

• Find Length of an array

new double[10]

double[] data = new double[10];

Continued…

System.out.println (data.length);

Page 7: Chapter 7 Arrays and Array Lists

Arrays

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

Page 8: Chapter 7 Arrays and Array Lists

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

Page 9: Chapter 7 Arrays and Array Lists

Arrays

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

Page 10: Chapter 7 Arrays and Array Lists

Arrays

Figure 1:An Array Reference and an Array

Page 11: Chapter 7 Arrays and Array Lists

Arrays• Use [ ] to access an element

Figure 2:Storing a Value in an Array

data[2] = 29.95;

Page 12: Chapter 7 Arrays and Array Lists

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

Continued…

Array Name

Page 13: Chapter 7 Arrays and Array Lists

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

}}

Page 14: Chapter 7 Arrays and Array Lists

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

Page 15: Chapter 7 Arrays and Array Lists

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

Page 16: Chapter 7 Arrays and Array Lists

Self Check1. 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;

Page 17: Chapter 7 Arrays and Array Lists

Self Check2. 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.

3. 0 4. a runtime error: array index out of bounds3. a compile-time error: c is not initialized

1. double[] a = new double[10]; System.out.println(a[0]);

2. double[] b = new double[10]; System.out.println(b[10]);

3. double[] c; System.out.println(c[0]);

Page 18: Chapter 7 Arrays and Array Lists

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…

Page 19: Chapter 7 Arrays and Array Lists

Copying Arrays: Copying Array References

Figure 7:Two References to the Same Array

Page 20: Chapter 7 Arrays and Array Lists

Copying Arrays: Cloning Arrays

• Use clone to make true copy

double[] prices = (double[]) data.clone();

Continued…

Need to cast as a (double) since cloned type is an Object

Page 21: Chapter 7 Arrays and Array Lists

Copying Arrays: Cloning Arrays

Figure 8:Cloning an Array

Page 22: Chapter 7 Arrays and Array Lists

Copying Arrays: Copying Array Elements

Continued…

System.arraycopy(from, fromStart, to, toStart, count);

From Array Name

ToArray Name

How many elements to copy

Page 23: Chapter 7 Arrays and Array Lists

Copying Arrays: Copying Array Elements

Figure 9:The System.arraycopy Method

Page 24: Chapter 7 Arrays and Array Lists

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.

Page 25: Chapter 7 Arrays and Array Lists

Growing an Array

• If the array is full and you need more space, you can grow the array:

1. Create a new, larger array.

2. Copy all elements into the new array

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

Page 26: Chapter 7 Arrays and Array Lists

Arrays

• You must allocate a larger array and copy the elements from the original array to the larger array.

data newData

free spaceBy setting data = newDatathe array data now references the copy.

Page 27: Chapter 7 Arrays and Array Lists

Growing an Array

Figure 12:Growing an Array

Page 28: Chapter 7 Arrays and Array Lists

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;

Page 29: Chapter 7 Arrays and Array Lists

Simple Array Algorithms: Finding the Maximum or Minimum

Steps -- Ex. Find the largest bank acct balance

1. Initialize a candidate with the starting element 2. Compare candidate with remaining elements 3. Update it if you find a larger or smaller value

Continued…

Page 30: Chapter 7 Arrays and Array Lists

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;

Page 31: Chapter 7 Arrays and Array Lists

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

Page 32: Chapter 7 Arrays and Array Lists

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?

Page 33: Chapter 7 Arrays and Array Lists

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!

Page 34: Chapter 7 Arrays and Array Lists

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

"Too Many Daves"

Page 35: Chapter 7 Arrays and Array Lists

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!

Page 36: Chapter 7 Arrays and Array Lists

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.

Page 37: Chapter 7 Arrays and Array Lists

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.

Page 38: Chapter 7 Arrays and Array Lists

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.

Page 39: Chapter 7 Arrays and Array Lists

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.

Page 40: Chapter 7 Arrays and Array Lists

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.

Page 41: Chapter 7 Arrays and Array Lists

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.

Page 42: Chapter 7 Arrays and Array Lists

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

Page 43: Chapter 7 Arrays and Array Lists

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…

Page 44: Chapter 7 Arrays and Array Lists

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

Page 45: Chapter 7 Arrays and Array Lists

Adding Elements

• set overwrites an existing value

• add adds a new value before the index

Continued…

BankAccount anAccount = new BankAccount(1729);accounts.set(2, anAccount);

accounts.add(i, a)

Page 46: Chapter 7 Arrays and Array Lists

Adding Elements

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

Page 47: Chapter 7 Arrays and Array Lists

Removing Elements

• remove removes an element at an index

Continued…

Accounts.remove(i)

Page 48: Chapter 7 Arrays and Array Lists

Removing Elements

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

Page 49: Chapter 7 Arrays and Array Lists

File: ArrayListTester.java - p294-296

01: import java.util.ArrayList;02: 03: /**04: This program tests the ArrayList class.05: */06: public class ArrayListTester07: {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…

Page 50: Chapter 7 Arrays and Array Lists

File: ArrayListTester.java17: 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: }

Outputsize=3first account number=1008last account number=1729

Page 51: Chapter 7 Arrays and Array Lists

Self Check

3. How do you construct an array of 10 strings? An array list of strings?

Ans: new String[10];

new ArrayList<String>();

Page 52: Chapter 7 Arrays and Array Lists

Self Check Continued…

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

Page 53: Chapter 7 Arrays and Array Lists

Wrappers

• You cannot insert primitive types directly into array lists

• To treat primitive type values as objects, you must use wrapper classes:

Continued…

ArrayList<Double> data = new ArrayList<Double>();data.add(29.95);double x = data.get(0);

Page 54: Chapter 7 Arrays and Array Lists

Wrappers

Figure 5:An Object of a Wrapper Class

Page 55: Chapter 7 Arrays and Array Lists

Wrappers

• There are wrapper classes for all eight primitive types

Page 56: Chapter 7 Arrays and Array Lists

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…

Page 57: Chapter 7 Arrays and Array Lists

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;

Page 58: Chapter 7 Arrays and Array Lists

Self Check5. What is the difference between the types

double and Double? Ans:

double is one of the eight primitive types. Double is a class type.

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

Page 59: Chapter 7 Arrays and Array Lists

The Enhanced for Loop• Traverses all elements of a collection:

Continued…

double[] data = . . .;double sum = 0;for (double e : data) // You should read this loop as // "for each e in data"{ sum += e;}

Page 60: Chapter 7 Arrays and Array Lists

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

Page 61: Chapter 7 Arrays and Array Lists

The Enhanced for Loop• Works for ArrayLists too:

ArrayList<BankAccount> accounts = . . . ;double sum = 0;for (BankAccount a : accounts){ sum += a.getBalance();}

Page 62: Chapter 7 Arrays and Array Lists

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

Page 63: Chapter 7 Arrays and Array Lists

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.

Page 64: Chapter 7 Arrays and Array Lists

Self Check7. Write a "for each" loop that prints all elements in the array

data Ans:

8. 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 (int i = 0; i < data.length; i++) data[i] = i * i;

for (double x : data) System.out.println(x);

Page 65: Chapter 7 Arrays and Array Lists

Simple Array Algorithms: Counting Matches

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

Textbook Page 303-305

Page 66: Chapter 7 Arrays and Array Lists

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

Page 67: Chapter 7 Arrays and Array Lists

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

Page 68: Chapter 7 Arrays and Array Lists

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

Page 69: Chapter 7 Arrays and Array Lists

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

Page 70: Chapter 7 Arrays and Array Lists

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] = " ";

Page 71: Chapter 7 Arrays and Array Lists

A Tic-Tac-Toe Board

Figure 6:A Tic-Tac-Toe Board

Page 72: Chapter 7 Arrays and Array Lists

Self Check

11.How do you declare and initialize a 4-by-4 array of integers?

ans: int[][] array = new int[4][4]

Page 73: Chapter 7 Arrays and Array Lists

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

Regression Testing

Page 74: Chapter 7 Arrays and Array Lists

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

Page 75: Chapter 7 Arrays and Array Lists

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.

Self Check 7.16

Page 76: Chapter 7 Arrays and Array Lists

Arrays/ Array lists

Applications?

Page 77: Chapter 7 Arrays and Array Lists

What to do with arrays….

• Input– Get “stuff” into our array

• Process– Do something with the stuff in our array

• Output– Display contents of our array

How?

What?

Where?

Page 78: Chapter 7 Arrays and Array Lists

Input// filling arrays with consecutive integersfor (count = 0;count < 20;count++){ v[count] = count ;

}

// filling array list with consecutive integersfor (count = 0;count < 20;count++){ v.add(new Integer(count));

}

Page 79: Chapter 7 Arrays and Array Lists

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

Page 80: Chapter 7 Arrays and Array Lists

while(count < maxCount && input.hasNextInt())

{ int a = input.nextInt(); arr[count] = a;count++;

} size = count; //number of filled elements

Page 81: Chapter 7 Arrays and Array Lists

Input// filling array list from fileArrayList<Integer> arr = new ArrayList<Integer>();while(input.hasNextInt()) {

int a = input.nextInt(); if (input.hasNextInt()){ arr.add(a);}

}

Page 82: Chapter 7 Arrays and Array Lists

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

Page 83: Chapter 7 Arrays and Array Lists

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?

Page 84: Chapter 7 Arrays and Array Lists

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

}

What about filling our 20-element container with random integers from 1 to 100 --

ArrayList?

Page 85: Chapter 7 Arrays and Array Lists

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

Page 86: Chapter 7 Arrays and Array Lists

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!

Page 87: Chapter 7 Arrays and Array Lists

Solution 1 :• 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

48623 *8

Page 88: Chapter 7 Arrays and Array Lists

Solution 1 :• 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?

48623 *8

Page 89: Chapter 7 Arrays and Array Lists

Solution 1 :• 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

48623 *8

Page 90: Chapter 7 Arrays and Array Lists

Solution 2:• 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”

Page 91: Chapter 7 Arrays and Array Lists

Solution 2 : a picture

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

48

b[0] 0b[1] 0b[2] 0b[3] 0b[4] 1b[5] 0b[6] 0b[7] 0b[8] 1b[9] 0b[10] 0b[11] 0

ab

Page 92: Chapter 7 Arrays and Array Lists

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

Page 93: Chapter 7 Arrays and Array Lists

Solution 3 : a picture

n= 100for (int k=0; k < 20; k++)

Choose a random number, r, in the range [1, n] 4Put b[r] in your arrayb[n] replaces b[r]Decrement n n = 99

4

b[0] 0b[1] 1b[2] 2b[3] 3b[4] 4100b[5] 5b[6] 6b[7] 7b[8] 8b[9] 9b[10] 10b[11] 11

A

Page 94: Chapter 7 Arrays and Array Lists

Solution 4:• 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]

Page 95: Chapter 7 Arrays and Array Lists

Solution 4 : a picture

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

b[0] 1b[1] 2b[2] 3b[3] 4b[4] 5 b[5] 6b[6] 7b[7] 8b[8] 9b[9] 10b[10] 11b[11] 12

5

1

Page 96: Chapter 7 Arrays and Array Lists

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.

Page 97: Chapter 7 Arrays and Array Lists

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.

12345678910

1234567910

1345679

10

82

Page 98: Chapter 7 Arrays and Array Lists

Other solutions ???

• • • • • •

Page 99: Chapter 7 Arrays and Array Lists

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

Page 100: Chapter 7 Arrays and Array Lists

Now……….• Our array is filled

– (by some obscure method)

• Let’s process…….– Find the sum.– Find the mean.– Find the largest/smallest value.– Many other things we can do….

Page 101: Chapter 7 Arrays and Array Lists

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

Page 102: Chapter 7 Arrays and Array Lists

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 largereturns a value = 0 if tempLarge is equal to largereturns a value > 0 if tempLarge is greater than large

Page 103: Chapter 7 Arrays and Array Lists

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

Page 104: Chapter 7 Arrays and Array Lists

3 5 6 8 3 0 0 4 4 4 2 3 3 3 3 3 9 9 9for ( 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

Page 105: Chapter 7 Arrays and Array Lists

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)

Page 106: Chapter 7 Arrays and Array Lists

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

Page 107: Chapter 7 Arrays and Array Lists

Initializer Listsint[] arr = {10, 20, 30, 40, 50, 60, 70, 80}; // Initializer list

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

Page 108: Chapter 7 Arrays and Array Lists

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.

Page 109: Chapter 7 Arrays and Array Lists

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)

Page 110: Chapter 7 Arrays and Array Lists

A word about efficiency

• Problem:– Insert it as the first element. O(n)

Page 111: Chapter 7 Arrays and Array Lists

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

Page 112: Chapter 7 Arrays and Array Lists

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

Page 113: Chapter 7 Arrays and Array Lists

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

Page 114: Chapter 7 Arrays and Array Lists

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]; CORRECTarrayName[0] = newValue;

newValue = 90;12 13 14 88 45 32 17 __ __ __

Page 115: Chapter 7 Arrays and Array Lists

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

Page 116: Chapter 7 Arrays and Array Lists

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.

Page 117: Chapter 7 Arrays and Array Lists

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.

Page 118: Chapter 7 Arrays and Array Lists

Make Parallel Arrays into Arrays of Objects

Figure 13:Avoid Parallel Arrays

// Don't do thisint[] accountNumbers;double[] balances;

Page 119: Chapter 7 Arrays and Array Lists

Make Parallel Arrays into Arrays of Objects

• Avoid parallel arrays by changing them into arrays of objects:

Figure 14:Reorganizing Parallel Arrays into Arrays of Objects

BankAccount[] = accounts;

Page 120: Chapter 7 Arrays and Array Lists

java.ioBufferedInputStream 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?

Page 121: Chapter 7 Arrays and Array Lists

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.

Page 122: Chapter 7 Arrays and Array Lists

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 fileboolean isDirectory() //tests if file is a directoryFile[ ] listFiles() // Returns an array of abstract pathnames denoting

//the files in the directory

String pathname = "../Data/words.txt“;File file = new File(pathname);

Page 123: Chapter 7 Arrays and Array Lists

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

Page 124: Chapter 7 Arrays and Array Lists

Scanner Methods

boolean hasNextLine()String nextLine()boolean hasNext()String next()boolean hasNextInt()int nextInt()boolean hasNextDouble()double nextDouble()void close()

Reads one word

Page 125: Chapter 7 Arrays and Array Lists

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(); Required to flush

the output buffer

Page 126: Chapter 7 Arrays and Array Lists

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?

Page 127: Chapter 7 Arrays and Array Lists

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


Recommended