0% found this document useful (0 votes)
58 views87 pages

Arrays

Arrays allow storing multiple values of the same type in an ordered list. An array has a single name and uses numeric indexes to access individual elements. Elements can be accessed, assigned, printed, or used in calculations using the array name and index in brackets. Arrays are objects that must be instantiated with the new keyword, specifying the size. The length property returns the number of elements in the array. Indexes must be within bounds or an exception is thrown. Arrays can be passed as parameters to methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views87 pages

Arrays

Arrays allow storing multiple values of the same type in an ordered list. An array has a single name and uses numeric indexes to access individual elements. Elements can be accessed, assigned, printed, or used in calculations using the array name and index in brackets. Arrays are objects that must be instantiated with the new keyword, specifying the size. The length property returns the number of elements in the array. Indexes must be within bounds or an exception is thrown. Arrays can be passed as parameters to methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 87

Chapter 7

Arrays…
Arrays
• An array is an ordered list of values

The entire array Each value has a numeric index


has a single name

0 1 2 3 4 5 6 7 8 9

scores 79 87 94 82 67 98 87 81 74 91

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

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

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

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

7-4
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
7-5
Arrays
• Another way to depict the scores array:

scores 79
87
94
82
67
98
87
81
74
91

7-6
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)
7-7
Declaring Arrays
• Some other examples of array declarations:

float[] prices = new float[500];

boolean[] flags;
flags = new boolean[20];

char[] codes = new char[1750];

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

7-9
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 + " ");

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

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

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


codes[index] = index*50 + epsilon;

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

• See LetterCount.java

7-13
ReverseOrder
Scanner 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] + " ");

7-14
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
7-15
Char Type
for(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:'?' 7-16
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();

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

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

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

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

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

7-22
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 + " ");

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

7-24
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 + " ");

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

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

7-27
• Previous Code using string array:

String[] sts3 = new String[3];


System.out.println(sts3[0]);
sts3[0] = new String("abc");

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

7-29
Arrays of Objects
• After some String objects are created and stored
in the array:

words “friendship
”“loyalty”

“honor”

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

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

7-32
Grade
public 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;
}
}

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

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

7-35
Example Use
String[] 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);

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

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

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

7-41
Using static variables
class 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++;
}

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

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

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

7-45
Arrays of Objects
• A UML diagram for the Tunes program:

Tunes CDCollection
- collection : CD[]
+ main (args : String[]) : void - count : int
- totalCost : double

+ addCD (title : String, artist : String,


cost : double, tracks : int) : void
+ toString() : String
CD - increaseSize() : void

- title : String 1
- artist : String
- cost : double
- tracks : int
*
+ toString() : String

7-46
CDCollection
public 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;
}

7-47
//-----------------------------------------------------------------
// 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++;
}

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

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

7-50
ArrayList class
ArrayList 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());

7-51
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.
7-52
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);
}

7-53

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

7-54
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>";
}
7-55
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);
}
}
7-56
Video…
public class Video
{
private String title;
private String director;
private int playingTime;
private boolean gotIt;
private String comment;

7-57
Database
public 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);
}

7-58
/**
* 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
}
} 7-59
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”);

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


7-61
// parallel array implementation
class PhoneBook0 {

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

public PhoneBook0(int initialCapacity) {


names = new String[initialCapacity];
numbers = new String[initialCapacity];
count = 0;
}

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

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

7-64
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;
}
7-65
ArrayList Implementation
class 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);
} 7-66
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;
} 7-67
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 : --

7-68
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;
}
}
7-69
// PhoneRecord implementation
class 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;
}
7-70
public String getNumber(String name) {
int loc = findName(name);
if (loc != -1)
return ((PhoneRecord) records.get(loc)).getNumber();
else
return null;
}

public String toString() {


String report = "";
Iterator it = records.iterator ();
while (it.hasNext()) {
PhoneRecord record = (PhoneRecord) it.next();
report += record.toString () + "\n";
}

return report;
}
7-71
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;
}

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

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

7-74
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”); 7-75
//hashmap implementation
class 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;
}

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

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

one two
dimension dimensions

7-79
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
7-80
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)

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

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

7-83
Debugger View

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

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

7-86
3 dimensional array
int [][][] table3 = { { {1,2}, {3,4} },
{ {5,6,7} , {8}, {9,10} }
};

7-87

You might also like