Top Banner
Chapter 7 Arrays…
87

Chapter 7

Jan 07, 2016

Download

Documents

La_Vey

Chapter 7. Arrays…. The entire array has a single name. Each value has a numeric index. 79 87 94 82 67 98 87 81 74 91. scores. Arrays. An array is an ordered list of values. 0 1 2 3 4 5 6 7 8 9. - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 7

Chapter 7

Arrays…

Page 2: Chapter 7

7-2

Arrays

• An array is an ordered list of values

0 1 2 3 4 5 6 7 8 9

79 87 94 82 67 98 87 81 74 91

An array of size N is indexed from zero to N-1

scores

The entire arrayhas a single name

Each value has a numeric index

This array holds 10 values that are indexed from 0 to 9

Page 3: Chapter 7

7-3

Arrays

• A particular value in an array is referenced using the array name followed by the index in brackets

• For example, the expression

scores[2]

refers to the value 94 (the 3rd value in the array)

• That expression represents a place to store a single integer and can be used wherever an integer variable can be used

Page 4: Chapter 7

7-4

Arrays

• For example, an array element can be assigned a value, printed, or used in a calculation:

scores[2] = 89;

scores[first] = scores[first] + 2;

mean = (scores[0] + scores[1])/2;

System.out.println ("Top = " + scores[5]);

Page 5: Chapter 7

7-5

Arrays• The values held in an array are called array

elements

• An array stores multiple values of the same type – the element type

• The element type can be a primitive type or an object reference

• Therefore, we can create an array of integers, an array of characters, an array of String objects, an array of Coin objects, etc.

• In Java, the array itself is an object that must be instantiated

Page 6: Chapter 7

7-6

Arrays

• Another way to depict the scores array:

scores 79

87

94

82

67

98

87

81

74

91

Page 7: Chapter 7

7-7

Declaring Arrays

• The scores array could be declared as follows:

int[] scores = new int[10];

• The type of the variable scores is int[] (an array of integers)

• Note that the array type does not specify its size, but each object of that type has a specific size

• The reference variable scores is set to a new array object that can hold 10 integers

• An array is an object, therefore all the values are initialized to default ones (here 0)

Page 8: Chapter 7

7-8

Declaring Arrays

• Some other examples of array declarations:

float[] prices = new float[500];

boolean[] flags;

flags = new boolean[20];

char[] codes = new char[1750];

Page 9: Chapter 7

7-9

Using Arrays

• The iterator version of the for loop can be used when processing array elements

for (int score : scores) System.out.println (score);

• This is only appropriate when processing all array elements from top (lowest index) to bottom (highest index)

• See BasicArray.java (page 372)

Page 10: Chapter 7

7-10

final int LIMIT = 15, MULTIPLE = 10;

int[] list = new int[LIMIT];

// Initialize the array values

for (int index = 0; index < LIMIT; index++)

list[index] = index * MULTIPLE;

list[5] = 999; // change one array value

// Print the array values

for (int value : list)

System.out.print (value + " ");

Page 11: Chapter 7

7-11

Bounds Checking

• Once an array is created, it has a fixed size

• An index used in an array reference must specify a valid element

• That is, the index value must be in range 0 to N-1

• The Java interpreter throws an ArrayIndexOutOfBoundsException if an array index is out of bounds

• This is called automatic bounds checking

Page 12: Chapter 7

7-12

Bounds Checking

• For example, if the array codes can hold 100 values, it can be indexed using only the numbers 0 to 99

• If the value of count is 100, then the following reference will cause an exception to be thrown:

System.out.println (codes[count]);

• It’s common to introduce off-by-one errors when using arrays

for (int index=0; index <= 100; index++)codes[index] = index*50 + epsilon;

problem

Page 13: Chapter 7

7-13

Bounds Checking

• Each array object has a public constant called length that stores the size of the array

• It is referenced using the array name:

scores.length

• Note that length holds the number of elements, not the largest index

• See ReverseOrder.java (page 375)

• See LetterCount.java (page 376)

Page 14: Chapter 7

7-14

ReverseOrderScanner scan = new Scanner (System.in);

double[] numbers = new double[10];

System.out.println ("The size of the array: " + numbers.length);

for (int index = 0; index < numbers.length; index++) { System.out.print ("Enter number " + (index+1) + ": "); numbers[index] = scan.nextDouble();} System.out.println ("The numbers in reverse order:");

for (int index = numbers.length-1; index >= 0; index--) System.out.print (numbers[index] + " ");

Page 15: Chapter 7

7-15

Char type

String st = "abcd";

for(int i =0; i < st.length (); i++ ) {

char c = st.charAt (i);

System.out.print(c);

System.out.print(" ");

System.out.print((int) c);

System.out.print(" ");

System.out.println(c - 'a');

}

a 97 0

b 98 1

c 99 2

Page 16: Chapter 7

7-16

Char Typefor(int i =40; i < 130; i++) {

System.out.print(i + ":\'" + (char) i + "\'\t");

if ((i+1) % 10 == 0)

System.out.println();

}

40:'(' 41:')' 42:'*' 43:'+' 44:',' 45:'-' 46:'.' 47:'/' 48:'0' 49:'1'

50:'2' 51:'3' 52:'4' 53:'5' 54:'6' 55:'7' 56:'8' 57:'9' 58:':' 59:';'

60:'<' 61:'=' 62:'>' 63:'?' 64:'@' 65:'A' 66:'B' 67:'C' 68:'D' 69:'E'

70:'F' 71:'G' 72:'H' 73:'I' 74:'J' 75:'K' 76:'L' 77:'M' 78:'N' 79:'O'

80:'P' 81:'Q' 82:'R' 83:'S' 84:'T' 85:'U' 86:'V' 87:'W' 88:'X' 89:'Y'

90:'Z' 91:'[' 92:'\' 93:']' 94:'^' 95:'_' 96:'`' 97:'a' 98:'b' 99:'c'

100:'d' 101:'e' 102:'f' 103:'g' 104:'h' 105:'i' 106:'j' 107:'k' 108:'l' 109:'m'

110:'n' 111:'o' 112:'p' 113:'q' 114:'r' 115:'s' 116:'t' 117:'u' 118:'v' 119:'w'

120:'x' 121:'y' 122:'z' 123:'{' 124:'|' 125:'}' 126:'~' 127:'' 128:'?' 129:'?' �

Page 17: Chapter 7

7-17

Letter Count

final int NUMCHARS = 26;

Scanner scan = new Scanner (System.in);

int[] upper = new int[NUMCHARS];

int[] lower = new int[NUMCHARS];

char current; // the current character being processed

int other = 0; // counter for non-alphabetics

System.out.println ("Enter a sentence:");

String line = scan.nextLine();

Page 18: Chapter 7

7-18

Letter Count

// Count the number of each letter occurence for (int ch = 0; ch < line.length(); ch++) { current = line.charAt(ch); if (current >= 'A' && current <= 'Z') upper[current-'A']++; else if (current >= 'a' && current <= 'z') lower[current-'a']++; else other++; }

Page 19: Chapter 7

7-19

Letter Count

// Print the results

System.out.println ();

for (int letter=0; letter < upper.length; letter++)

{

System.out.print ( (char) (letter + 'A') );

System.out.print (": " + upper[letter]);

System.out.print ("\t\t" + (char) (letter + 'a') );

System.out.println (": " + lower[letter]);

}

System.out.println ();

System.out.println ("Non-alphabetic characters: " + other);

Page 20: Chapter 7

7-20

Alternate Array Syntax

• The brackets of the array type can be associated with the element type or with the name of the array

• Therefore the following two declarations are equivalent:

float[] prices;

float prices[];

• The first format generally is more readable and should be used

Page 21: Chapter 7

7-21

Initializer Lists

• An initializer list can be used to instantiate and fill an array in one step

• The values are delimited by braces and separated by commas

• Examples:

int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476};

char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};

Page 22: Chapter 7

7-22

Initializer Lists

• Note that when an initializer list is used:

the new operator is not used

no size value is specified

• The size of the array is determined by the number of items in the initializer list

• An initializer list can be used only in the array declaration

• See Primes.java (page 381)

Page 23: Chapter 7

7-23

Primes

int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19};

System.out.println ("Array length: " + primeNums.length);

System.out.println ("The first few prime numbers are:");

for (int prime : primeNums)

System.out.print (prime + " ");

Page 24: Chapter 7

7-24

Arrays as Parameters

• An entire array can be passed as a parameter to a method

• Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other

• Therefore, changing an array element within the method changes the original

• An individual array element can be passed to a method as well, in which case the type of the formal parameter is the same as the element type

Page 25: Chapter 7

7-25

Arrays as Parameters

public static void doubleValues(int[] x) {

for (int i = 0; i < x.length; i++) {

x[i] *= 2;

}

}

int[] x = {1, 3, 5};

doubleValues(x);

for(int val:x)

System.out.print(val + " ");

Page 26: Chapter 7

7-26

Arrays of Objects

• Consider:

class String3 {

String value0, value1, value2;

}

String3 sts3 = new String3();

System.out.println(sts3.value0); // outputs null

sts3.value0 = new String("abc");

Page 27: Chapter 7

7-27

Arrays of Objects

• The elements of an array can be object references

• The following declaration reserves space to store 3 references to String objects

String[] words = new String[3];

• It does NOT create the String objects themselves

• Initially an array of objects holds null references

• Each object stored in an array must be instantiated separately

Page 28: Chapter 7

7-28

• Previous Code using string array:

String[] sts3 = new String[3];

System.out.println(sts3[0]);

sts3[0] = new String("abc");

Page 29: Chapter 7

7-29

Arrays of Objects

• The words array when initially declared:

words -

-

-

• At this point, the following reference would throw a NullPointerException:

System.out.println (words[0].length());

Page 30: Chapter 7

7-30

Arrays of Objects

• After some String objects are created and stored in the array:

“friendship”

words

“loyalty”

“honor”

Page 31: Chapter 7

7-31

Arrays of Objects

• Keep in mind that String objects can be created using literals

• The following declaration creates an array object called verbs and fills it with four String objects created using string literals

String[] verbs = {"play", "work", "eat", "sleep"};

Page 32: Chapter 7

7-32

Array of Objects

• The following example creates an array of Grade objects, each with a string representation and a numeric lower bound

• See GradeRange.java (page 384)• See Grade.java (page 385)

Page 33: Chapter 7

7-33

Gradepublic class Grade { private String name; private int lowerBound;

//----------------------------------------------------------------- // Constructor: Sets up this Grade object with the specified // grade name and numeric lower bound. //----------------------------------------------------------------- public Grade (String grade, int cutoff) { name = grade; lowerBound = cutoff; }

//----------------------------------------------------------------- // Returns a string representation of this grade. //----------------------------------------------------------------- public String toString() { return name + "\t" + lowerBound; }}

Page 34: Chapter 7

7-34

Grade[] grades =

{

new Grade("A", 95), new Grade("A-", 90),

new Grade("B+", 87), new Grade("B", 85), new Grade("B-", 80),

new Grade("C+", 77), new Grade("C", 75), new Grade("C-", 70),

new Grade("D+", 67), new Grade("D", 65), new Grade("D-", 60),

new Grade("F", 0)

};

for (Grade letterGrade : grades)

System.out.println (letterGrade);

Page 35: Chapter 7

7-35

CD Collection

• Let’s write methods that will help us maintain information about music CD’s.

• Specifically, we want to keep track of the title, the artist name, and price of each CD.

• Let’s keep these information in three different arrays, titles, artists, and prices.

• The idea is the same location i is used for storing the information of CD number i in three different arrays.

• Write methods for adding a new CD, deleting one given its title, and displaying information given its title.

Page 36: Chapter 7

7-36

Example UseString[] ts = new String[100];String[] as = new String[100];double[] prices = new double[100];int count = 0;CDCollection.addCD("title1", "artist1", 1,count, ts, as, prices);count++;CDCollection.addCD("title2", "artist2", 2,count, ts, as, prices);count++;CDCollection.addCD("title3", "artist3", 3,count, ts, as, prices);count++;

CDCollection.printCD("title3", count, ts, as, prices);

CDCollection.deleteCD("title2", count, ts, as, prices);count--;

CDCollection.printCD("title2", count, ts, as, prices);

Page 37: Chapter 7

7-37

public class CDCollection {

public static void addCD(String title, String artist, double price,int count, String[] titles, String[] artists, double[] prices) {titles[count] = title;artists[count] = artist;prices[count] = price;

}

public static boolean deleteCD(String title,int count,String[] titles, String[] artists, double[] prices) {

int loc = findCD(title, count, titles);if (loc == -1)

return false;for(int i = loc + 1; i < count; i++) {

titles[i-1] = titles[i];artists[i-1] = artists[i];prices[i-1] = prices[i];

}return true;

}

Page 38: Chapter 7

7-38

public static void printCD(String title,int count,String[] titles, String[] artists, double[] prices) {

int loc = findCD(title, count, titles);if (loc == -1)

System.out.println("CD not found");else

System.out.println("\n" + titles[loc] + " " +artists[loc] + " " + prices[loc]);

}

private static int findCD(String title,int count,String[] titles) {

for(int i = 0; i < count; i++)if (titles[i].equals(title))

return i;

return -1;}

Page 39: Chapter 7

7-39

Notes

• We can change the contents of the array, but not the primitive type int for count.

• It is not convenient for the user to maintain the count variable himself.

• One solution is to put the count into an int array• This way, the user can do :

String[] ts = new String[100];

String[] as = new String[100];

double[] prices = new double[100];

int[] count = new int[1];

CDCollection.addCD("title1", "artist1", 1,count, ts, as, prices);

Page 40: Chapter 7

7-40

public static void addCD(String title, String artist, double price,int[] count, String[] titles, String[] artists, double[] prices) {titles[count[0]] = title;artists[count[0]] = artist;prices[count[0]] = price;count[0]++;

}

public static boolean deleteCD(String title,int[] count,String[] titles, String[] artists, double[] prices) {

int loc = findCD(title, count[0], titles);if (loc == -1)

return false;for(int i = loc + 1; i < count[0]; i++) {

titles[i-1] = titles[i];artists[i-1] = artists[i];prices[i-1] = prices[i];

}count[0]--;return true;

}

Page 41: Chapter 7

7-41

Notes

• It is still inconvenient for the user to maintain the arrays and the count itself.

• We can let the class contain the arrays itself

Page 42: Chapter 7

7-42

Using static variablesclass CDCollection4 {

private static int count = 0;private static String[] titles = new String[100];private static String[] artists = new String[100];private static double[] prices = new double[100];

public static void addCD(String title, String artist, double price) {

titles[count] = title;artists[count] = artist;prices[count] = price;count++;

}

Page 43: Chapter 7

7-43

Using static variables

CDCollection.addCD("title1", "artist1", 1);

CDCollection.addCD("title2", "artist2", 2);

CDCollection.addCD("title3", "artist3", 3);

CDCollection.printCD("title3");

CDCollection.deleteCD("title2");

CDCollection.printCD("title2");

• Since the variables are static, and belong to the class (therefore there is only once copy), a program can only have one collection at a time.

Page 44: Chapter 7

7-44

Using Objects

• A better way is to make the variables and methods non-static, so that objects, not the class owns the information. So different objects will have their own arrays, letting one to use several collections at the same time

• We also improve the code so that it grows the storage area as the number of CDs exceed the capacity.

Page 45: Chapter 7

7-45

Using…

CDCollection cc1 = new CDCollection();

CDCollection cc2 = new CDCollection();

cc1.addCD("title1", "artist1", 1);

cc2.addCD("title2", "artist2", 2);

cc1.addCD("title3", "artist3", 3);

cc1.printCD("title3");

cc2.deleteCD("title2");

Page 46: Chapter 7

7-46

Arrays of Objects

• A UML diagram for the Tunes program:

Tunes

+ main (args : String[]) : void

CDCollection

- collection : CD[]- count : int- totalCost : double

+ addCD (title : String, artist : String, cost : double, tracks : int) : void+ toString() : String- increaseSize() : voidCD

- title : String- artist : String- cost : double- tracks : int

+ toString() : String

*

1

Page 47: Chapter 7

7-47

CDCollectionpublic class CDCollection{ private CD[] collection; private int count; private double totalCost;

//----------------------------------------------------------------- // Constructor: Creates an initially empty collection. //----------------------------------------------------------------- public CDCollection () { collection = new CD[100]; count = 0; totalCost = 0.0; }

Page 48: Chapter 7

7-48

//-----------------------------------------------------------------

// Adds a CD to the collection, increasing the size of the

// collection if necessary.

//-----------------------------------------------------------------

public void addCD (String title, String artist, double cost, int tracks)

{

if (count == collection.length)

increaseSize();

collection[count] = new CD (title, artist, cost, tracks);

totalCost += cost;

count++;

}

Page 49: Chapter 7

7-49

public String toString() { NumberFormat fmt = NumberFormat.getCurrencyInstance();

String report = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; report += "My CD Collection\n\n";

report += "Number of CDs: " + count + "\n"; report += "Total cost: " + fmt.format(totalCost) + "\n"; report += "Average cost: " + fmt.format(totalCost/count);

report += "\n\nCD List:\n\n";

for (int cd = 0; cd < count; cd++) report += collection[cd].toString() + "\n";

return report; }

Page 50: Chapter 7

7-50

//----------------------------------------------------------------- // Increases the capacity of the collection by creating a // larger array and copying the existing collection into it. //----------------------------------------------------------------- private void increaseSize () { CD[] temp = new CD[collection.length * 2];

for (int cd = 0; cd < collection.length; cd++) temp[cd] = collection[cd];

collection = temp; }}

Page 51: Chapter 7

7-51

ArrayList classArrayList band = new ArrayList();

band.add ("Paul"); band.add ("Pete");band.add ("John"); band.add ("George");

System.out.println (band);

int location = band.indexOf ("Pete");band.remove (location);

System.out.println (band);System.out.println ("At index 1: " + band.get(1));

band.add (2, "Ringo");

System.out.println (band);System.out.println ("Size : " + band.size());

Page 52: Chapter 7

7-52

Some ArrayList methods

boolean add(Object o) : Appends the specified element to the end of this Vector.

Object get(int index)  Returns the element at the specified position in this Vector.

String toString() :Returns a string representation of this Vector, containing the String representation of each element

Int indexOf(Object elem) : Searches for the first occurence of the given argument, testing for equality using the equals method.

Object remove(int index) : 

Removes the element at the specified position in this Vector.

 int size() : Returns the number of components in this vector.

Page 53: Chapter 7

7-53

CDCollection using ArrayList

import java.util.*;

public class CDCollection {

private ArrayList collection;

public CDCollection () {

collection = new ArrayList(100);

}

public void addCD (String title, String artist, double value, int tracks) {

CD newcd = new CD (title, artist, value, tracks);

collection.add (newcd);

}

Page 54: Chapter 7

7-54

public String toString() {String report = "";for (int cd = 0; cd < collection.size (); cd++) {

CD currentcd = (CD) collection.get (cd);report += currentcd.toString() + "\n";

}// or ….Iterator it = collection.iterator ();while (it.hasNext ()) {

CD currentcd = (CD) it.next ();report += currentcd.toString() + "\n";

}return report;

}

Page 55: Chapter 7

7-55

Video and CD Database Example

//author Michael Kolling and David J. Barnes (Objects First with Java)public class CD { private String title; private String artist; private int numberOfTracks; private int playingTime; private boolean gotIt; private String comment;

public CD(String theTitle, String theArtist, int tracks, int time) { title = theTitle; artist = theArtist; numberOfTracks = tracks; playingTime = time; gotIt = false; comment = "<no comment>"; }

Page 56: Chapter 7

7-56

CD.. public void setComment(String comment) { this.comment = comment; } public String getComment() { return comment; } public void setOwn(boolean ownIt) { …} public boolean getOwn() {…}

public void print() { System.out.print("CD: " + title + " (" + playingTime + " mins)"); if(gotIt) { System.out.println("*"); } else { System.out.println(); } System.out.println(" " + artist); System.out.println(" tracks: " + numberOfTracks); System.out.println(" " + comment); }}

Page 57: Chapter 7

7-57

Video…

public class Video

{

private String title;

private String director;

private int playingTime;

private boolean gotIt;

private String comment;

Page 58: Chapter 7

7-58

Databasepublic class Database { private ArrayList cds; private ArrayList videos;

// * Construct an empty Database. public Database() { cds = new ArrayList(); videos = new ArrayList(); }

/** * Add a CD to the database. */ public void addCD(CD theCD) { cds.add(theCD); }

/** * Add a video to the database. */ public void addVideo(Video theVideo) { videos.add(theVideo); }

Page 59: Chapter 7

7-59

/** * Print a list of all currently stored CDs and videos to the * text terminal. */ public void list() { // print list of CDs for(Iterator iter = cds.iterator(); iter.hasNext(); ) { CD cd = (CD)iter.next(); cd.print(); System.out.println(); // empty line between items }

// print list of videos for(Iterator iter = videos.iterator(); iter.hasNext(); ) { Video video = (Video)iter.next(); video.print(); System.out.println(); // empty line between items } }

Page 60: Chapter 7

7-60

PhoneBook example

• Implement a class that will act like a phone book: it will contain phone numbers along with their owners

• Typical use of the class will look like:

PhoneBook pb = new PhoneBook(10);

pb.add(“cengiz”, “312-290 3395”);

pb.add(“maintenance”, “555 2323 ext 43”);

…..

System.out.println(pb);

String deptNumber = b.getNumber(“department”);

pb.remove(“nofutur”);

Page 61: Chapter 7

7-61

Parallel Array Implementation

• Each phone entry consists of a key, the name or owner of the phone number, and the value, the phone number itself.

• We can create two arrays, names and numbers, to store these two pieces of information, such that numbers[i] is the phone number corresponding to names[i].

• Very similar to CDCollection example

• Need sequential scan to find a phone number

Page 62: Chapter 7

7-62

// parallel array implementationclass PhoneBook0 {

String[] names;String[] numbers;int count;

public PhoneBook0(int initialCapacity) {names = new String[initialCapacity];numbers = new String[initialCapacity];count = 0;

}

Page 63: Chapter 7

7-63

public void add(String name, String number) {

if (count == names.length) {

String [] newNames = new String[2 * names.length];

String [] newNumbers = new String[2 * numbers.length];

for(int i =0; i < names.length; i++) {

newNames[i] = names[i];

newNumbers[i] = numbers[i];

}

names = newNames;

numbers = newNumbers;

}

names[count] = name;

numbers[count] = number;

count++;

}

Page 64: Chapter 7

7-64

public boolean remove(String name) {int loc = findName(name);if (loc != -1) {

names[loc] = names[count - 1];numbers[loc] = numbers[count - 1];count--;return true;

}else

return false;}

public String getNumber(String name) {int loc = findName(name);if (loc != -1)

return numbers[loc];else

return null;}

Page 65: Chapter 7

7-65

public String toString() {String report = "";for(int i = 0; i < count; i++)

report += names[i] + " : " + numbers[i] + "\n";

return report;}

private int findName(String name){

int loc = count - 1;while (loc >= 0) {

String currName = names[loc];if (currName.equals(name))

break;loc --;

}

return loc;}

Page 66: Chapter 7

7-66

ArrayList Implementationclass PhoneBook1 {

ArrayList names;ArrayList numbers;

public PhoneBook1(int initialCapacity) {names = new ArrayList(initialCapacity);numbers = new ArrayList(initialCapacity);

}

public void add(String name, String number) {names.add (name);numbers.add(number);

}

Page 67: Chapter 7

7-67

public boolean remove(String name) {

int loc = names.indexOf (name);if (loc != -1) {

names.remove(loc);numbers.remove(loc);return true;

}else

return false;}

public String getNumber(String name) {int loc = names.indexOf (name);if (loc != -1)

return (String) numbers.get(loc);else

return null;}

public String toString() {String report = "";

Iterator nameit = names.iterator ();Iterator numberit = numbers.iterator ();while (nameit.hasNext ()) {

String name = (String) nameit.next();String number = (String) numberit.next();report += name + " : " + number + "\n";

}return report;

}

Page 68: Chapter 7

7-68

Parallel Array Implementation Overview

• Two separate collection to maintain• Prone to error

• What if we want to extend our solution so that there is not only one phone number, but several variation like home number, work number, mobile number? What changes do you need to do?

• It would be better if we wrap up all the phone related information to a separate class : --

Page 69: Chapter 7

7-69

class PhoneRecord {private String name;private String number;

public PhoneRecord(String name, String number) {this.name = name;this.number = number;

}

public String getName() {return name;

}

public String getNumber() {return number;

}

public String toString() {return name + " : " + number;

}}

Page 70: Chapter 7

7-70

// PhoneRecord implementationclass PhoneBook2 {

ArrayList records;

public PhoneBook2(int initialCapacity) {records = new ArrayList(initialCapacity);

}

public void add(String name, String number) {records.add( new PhoneRecord(name, number));

}

public boolean remove(String name) {int loc = findName(name);if (loc != -1) {

records.remove(loc);return true;

}else

return false;}

Page 71: Chapter 7

7-71

public String getNumber(String name) {int loc = findName(name);if (loc != -1)

return ((PhoneRecord) records.get(loc)).getNumber();

elsereturn null;

}

public String toString() {String report = "";Iterator it = records.iterator ();while (it.hasNext()) {

PhoneRecord record = (PhoneRecord) it.next();report += record.toString () + "\n";

}

return report;}

Page 72: Chapter 7

7-72

private int findName(String name){

int loc = records.size () - 1;while (loc >= 0) {

PhoneRecord currRecord = (PhoneRecord) records.get(loc);

if (currRecord.getName().equals(name))break;

loc --;}

return loc;}

Page 73: Chapter 7

7-73

Array Implementations Overview

• Relatively fast insertions• Iterating over the records simple• Records are sorted by their insertion time• If order needs to be preserved, removal is a

difficult process, otherwise deletions are fast, too.• Finding an item needs sequential search, therefore

not very efficient

Page 74: Chapter 7

7-74

HashMap implementation

• In our implementations, what we really have is just a mapping from a key to a value.

• Unfortunately, our arrays can only map an integer value to a value : Names[i] ~ i element at location I

It would be nice if arrays could be indexed by other types as well :

numbers[“cengiz”] ~ “cengiz” “312-290 3395”

Page 75: Chapter 7

7-75

HashMap Methods

• public Object put(Object key, Object value) Associates the specified value with the specified key in this

map. If the map previously contained a mapping for this key, the old value is replaced.

• public Object get(Object key) Returns the value to which the specified key is mapped in

this identity hash map, or null if the map contains no mapping for this key.

HashMap map = new HashMap();

Map.put(“cengiz”, “312-290 3395”);

….

String cengizNo = (String) map.get(“cengiz”);

Page 76: Chapter 7

7-76

//hashmap implementationclass PhoneBook3 {

public HashMap records;

public PhoneBook3(int initialCapacity) {records = new HashMap(initialCapacity);

}

public void add(String name, String number) {records.put (name, number);

}

public boolean remove(String name) {String number = (String) records.remove (name);return number != null;

}

Page 77: Chapter 7

7-77

public String getNumber(String name) {String number = (String) records.get(name);return number;

}

public String toString() {String report = "";

Set entrySet = records.entrySet();Iterator it = entrySet.iterator ();while (it.hasNext()) {

Map.Entry entry = (Map.Entry) it.next();report += (String) entry.getKey() + " : " +

(String)entry.getValue() + "\n";

}return report;

}

Page 78: Chapter 7

7-78

Alternative Iteration

public String toString() {

String report = "";

Set keys = records.keySet();

Iterator it = keys.iterator ();

while (it.hasNext()) {

String key = (String) it.next();

String value = (String) records.get(key);

report += (String) key + " : " + value + "\n";

}

return report;

}

Page 79: Chapter 7

7-79

Two-Dimensional Arrays

• A one-dimensional array stores a list of elements

• A two-dimensional array can be thought of as a table of elements, with rows and columns

onedimension

twodimensions

Page 80: Chapter 7

7-80

Two-Dimensional Arrays

• To be precise, in Java a two-dimensional array is an array of arrays

• A two-dimensional array is declared by specifying the size of each dimension separately:

int[][] scores = new int[12][50];

• A array element is referenced using two index values:

value = scores[3][6]

• The array stored in one row can be specified using one index

Page 81: Chapter 7

7-81

Two-Dimensional Arrays

Expression Type Description

table int[][] 2D array of integers, or

array of integer arrays

table[5] int[] array of integers

table[5][12] int integer

• See TwoDArray.java (page 399)

• See SodaSurvey.java (page 400)

Page 82: Chapter 7

7-82

TwoDArray

public static void main (String[] args) { int[][] table = new int[5][10];

// Load the table with values for (int row=0; row < table.length; row++) for (int col=0; col < table[row].length; col++) table[row][col] = row * 10 + col;

// Print the table for (int row=0; row < table.length; row++) { for (int col=0; col < table[row].length; col++) System.out.print (table[row][col] + "\t"); System.out.println(); }}

Page 83: Chapter 7

7-83

Output

0 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17 18 19

20 21 22 23 24 25 26 27 28 29

30 31 32 33 34 35 36 37 38 39

40 41 42 43 44 45 46 47 48 49

Page 84: Chapter 7

7-84

Debugger View

Page 85: Chapter 7

7-85

int[][] scores = { {3, 4, 5, 2, 1, 4, 3, 2, 4, 4}, {2, 4, 3, 4, 3, 3, 2, 1, 2, 2}, {3, 5, 4, 5, 5, 3, 2, 5, 5, 5}, {1, 1, 1, 3, 1, 2, 1, 3, 2, 4} };

final int SODAS = scores.length; final int PEOPLE = scores[0].length;

int[] sodaSum = new int[SODAS]; int[] personSum = new int[PEOPLE];

for (int soda=0; soda < SODAS; soda++) for (int person=0; person < PEOPLE; person++) { sodaSum[soda] += scores[soda][person]; personSum[person] += scores[soda][person]; }

Page 86: Chapter 7

7-86

Multidimensional Arrays

• An array can have many dimensions – if it has more than one dimension, it is called a multidimensional array

• Each dimension subdivides the previous one into the specified number of elements

• Each dimension has its own length constant

• Because each dimension is an array of array references, the arrays within one dimension can be of different lengths

these are sometimes called ragged arrays

Page 87: Chapter 7

7-87

3 dimensional array

int [][][] table3 = { { {1,2}, {3,4} },

{ {5,6,7} , {8}, {9,10} }

};