Chapter 7 Arrays and Array Lists

Preview:

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

Citation preview

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

new double[10]

double[] data = new double[10];

Continued…

System.out.println (data.length);

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

Figure 2:Storing a Value in an Array

data[2] = 29.95;

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

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

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

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

Continued…

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

Copying Arrays: Cloning Arrays

Figure 8:Cloning an Array

Copying Arrays: Copying Array Elements

Continued…

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

From Array Name

ToArray Name

How many elements to copy

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:

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;

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.

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

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…

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

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"

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.

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

Continued…

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

accounts.add(i, a)

Adding Elements

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

Removing Elements

• remove removes an element at an index

Continued…

Accounts.remove(i)

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

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

Self Check

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

Ans: new String[10];

new ArrayList<String>();

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

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

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

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

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

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

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

• 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

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

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

• 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

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

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

Arrays/ Array lists

Applications?

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?

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

}

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

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

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

} size = count; //number of filled elements

Input// filling array list from fileArrayList<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?

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?

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

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

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

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

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”

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

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

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

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]

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

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.

12345678910

1234567910

1345679

10

82

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

– (by some obscure method)

• Let’s process…….– 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 largereturns a value = 0 if tempLarge is equal to largereturns 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 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

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

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

Figure 13:Avoid Parallel Arrays

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

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;

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?

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.

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

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

Scanner Methods

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

Reads one word

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

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

Recommended