Arrays
Arrays
Arrays…
Arrays
• An array is an ordered list of values
0 1 2 3 4 5 6 7 8 9
scores 79 87 94 82 67 98 87 81 74 91
7-2
Arrays
• A particular value in an array is referenced using
the array name followed by the index in brackets
scores[2]
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;
7-4
Arrays
• The values held in an array are called array
elements
scores 79
87
94
82
67
98
87
81
74
91
7-6
Declaring Arrays
• The scores array could be declared as follows:
• Note that the array type does not specify its size,
but each object of that type has a specific size
boolean[] flags;
flags = new boolean[20];
7-8
Using Arrays
• The iterator version of the for loop can be used
when processing array elements
7-9
final int LIMIT = 15, MULTIPLE = 10;
7-10
Bounds Checking
• Once an array is created, it has a fixed size
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
System.out.println (codes[count]);
7-12
Bounds Checking
• Each array object has a public constant called
length that stores the size of the array
scores.length
• See ReverseOrder.java
• See LetterCount.java
7-13
ReverseOrder
Scanner scan = new Scanner (System.in);
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;
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
float[] prices;
float prices[];
7-20
Initializer Lists
• An initializer list can be used to instantiate and fill
an array in one step
• Examples:
7-21
Initializer Lists
• Note that when an initializer list is used:
the new operator is not used
7-22
Primes
int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19};
7-23
Arrays as Parameters
• An entire array can be passed as a parameter to a
method
7-24
Arrays as Parameters
public static void doubleValues(int[] x) {
for (int i = 0; i < x.length; i++) {
x[i] *= 2;
}
}
7-25
Arrays of Objects
• Consider:
class String3 {
String value0, value1, value2;
}
7-26
Arrays of Objects
• The elements of an array can be object references
7-27
• Previous Code using string array:
7-28
Arrays of Objects
• The words array when initially declared:
words -
-
-
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
7-31
Array of Objects
• The following example creates an array of Grade
objects, each with a string representation and a
numeric lower bound
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)
};
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++;
7-36
public class CDCollection {
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 :
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]++;
}
7-41
Using static variables
class CDCollection4 {
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");
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
7-44
Using…
CDCollection cc1 = new CDCollection();
CDCollection cc2 = new CDCollection();
7-45
Arrays of Objects
• A UML diagram for the Tunes program:
Tunes CDCollection
- collection : CD[]
+ main (args : String[]) : void - count : int
- totalCost : double
- 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();
7-48
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
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];
collection = temp;
}
}
7-50
ArrayList class
ArrayList band = new ArrayList();
System.out.println (band);
System.out.println (band);
System.out.println ("At index 1: " + band.get(1));
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.
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 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;
7-57
Database
public class Database {
private ArrayList cds;
private ArrayList videos;
/**
* 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
}
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.
String[] names;
String[] numbers;
int count;
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;
}
7-64
public String toString() {
String report = "";
for(int i = 0; i < count; i++)
report += names[i] + " : " + numbers[i] + "\n";
return report;
}
return loc;
}
7-65
ArrayList Implementation
class PhoneBook1 {
ArrayList names;
ArrayList numbers;
7-68
class PhoneRecord {
private String name;
private String number;
ArrayList records;
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
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.
7-76
public String getNumber(String name) {
String number = (String) records.get(name);
return number;
}
7-78
Two-Dimensional Arrays
• A one-dimensional array stores a list of elements
one two
dimension dimensions
7-79
Two-Dimensional Arrays
• To be precise, in Java a two-dimensional array is
an array of arrays
value = scores[3][6]
7-81
TwoDArray
public static void main (String[] args) {
int[][] table = new int[5][10];
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} };
7-85
Multidimensional Arrays
• An array can have many dimensions – if it has
more than one dimension, it is called a
multidimensional array
7-86
3 dimensional array
int [][][] table3 = { { {1,2}, {3,4} },
{ {5,6,7} , {8}, {9,10} }
};
7-87