Title: CS 2
1CS 2
- Introduction to
- Object Oriented Programming
- Chapter 13
- Arrays
2CHAPTER GOALS
- To become familiar with using vectors to store a
collection of objects - To learn about common array algorithms
- To be able to use arrays
- To understand when to choose vectors versus
arrays in your programs - To implement partially filled arrays
- To learn how to use two-dimensional arrays
3The Concept of an Array
- (1) A series of related items. (2) An ordered
arrangement or pattern of items or numbers, such
as a determinant, matrix, vector, or table of
numbers.Source Darcy, Laura. Webster's New
World Dictionary of Computer Terms. 3rd ,
Completely rev. updated. New York Webster's
New World, 1988. - An aggregate that consists of data objects, with
identical attributes, each of which may be
uniquely referenced by subscripting.Source
Nader, J. Prentice Hall's Illustrated Dictionary
of Computing. 2nd ed. Sydney New York Prentice
Hall, 1995. - An arrangement of data in one or more
dimensions a list, a table, or a
multidimensional arrangement of items.Source
McDaniel, George, and International Business
Machines Corporation. IBM Dictionary of
Computing. New York McGraw-Hill, 1994.
4Array Related Terminologies
- The name of an array
- Element
- Index, subscript
- Length, size, number elements
Source Oh Programming! by Saun Shewanown (to be
published by Prentice Hall)
5Array Elements
In this example, scoreArrayi (reads scoreArray
sub i) is equivalent to a variable of primitive
type float or double in Java. Therefore, we can
access the value of and assign a value to
scoreArrayi. e.g. System.out.println(scoreArra
y0) scoreArray0 23.1
Source Oh Programming! by Saun Shewanown (to be
published by Prentice Hall)
6Array Implementations in Java
- Java offers ways to implement Arrays
- basic array (Section 13.4 of the textbook)
- ArrayList class (chapter 13 of the textbook,
java.util in Java API) - Vector class (java.util in Java API)
- Many Others (java.util in Java API)
We will cover basic array and Vector (instead of
ArrayList). Note There are minor distinctions
between ArrayList and Vector class. The
distinctions between the two classes have no
impact on our course. The discussion in chapter
13 is relevant to both ArrayList and Vector
class. A Vector class version of chapter 13
source code is posted on the Lecture Slides page
of the course web site.
7Arrays (Java basic arrays)
- Construct array
- new double10
- Store in variable of type double double data
new double10
8Arrays (Java basic arrays)
- Arrays have fixed length
- Arrays have element of specific type, not Object
- Use to access elementdata4 29.95
- Get array length as data.length. (Not a method!)
9Syntax 13.1 Array Construction
- new typenamelength
- Example
- new double10
- Purpose
- To construct an array with a given number of
elements.
10Syntax 13.2 Array Element Access
- arrayReferenceindex
- Example
- a4 29.95 double x a4
-
- Purpose
- To access an element in an array
11ScoreArrayTest.java
- import javax.swing.JOptionPane
- class ScoreArray
- // This class is used to demonstrate the use
of - // Java primitive arrays and parameter
passing. - // It does NOT follow O-O conventions
- public void calculateScores()
- double scoreArray new double100
- int scoreCount 0
- double average 0
-
- scoreCount promptScores(scoreArray)
- average getAverage(scoreArray,
scoreCount) - displayScores(scoreArray, scoreCount,
average) - // calculateScores
12ScoreArrayTest.java
- void displayScores(double scoreArray, int
scoreCount,
double average) - System.out.println("Entered scores
are") -
- for(int i0 iltscoreCount i)
- System.out.println("Score " (i1)
" " scoreArrayi) -
-
- System.out.println("The average score "
average) -
- // displayScores
13ScoreArrayTest.java
- public double getAverage(double
numberArray, int elementCount) - return getSum(numberArray, elementCount)
/ elementCount - // getSum()
-
- public double getSum(double numberArray,
int elementCount) - double sum 0
-
- for(int i0 iltelementCount i)
- sum numberArrayi
-
-
- return sum
- // getSum()
14ScoreArrayTest.java
- public int promptScores(double
numberArray) - int scoreCount 0
- String enteredString
-
- do
- enteredString JOptionPane.showInputD
ialog("Enter a score") -
- if(enteredString ! null)
- numberArrayscoreCount
Double.parseDouble(enteredString) - scoreCount
-
-
- while(enteredString ! null)
-
- return scoreCount
- // promptScores()
- // ScoreArray
- class ScoreArrayTest
- public static void main(String args)
- ScoreArray a new ScoreArray()
- a.calculateScores()
-
- // ScoreArrayTest
15(No Transcript)
16Array of Objects
- class ShapeArrayDemo
- public ShapeArrayDemo()
- Shape shapeArray new Shape100
- int count 0
-
- shapeArray0 new Circle(1, 2, 3)
- count
- shapeArray1 new Rectangle(1, 2, 3,
4) - count
- shapeArray2 new Triangle(1, 2, 3, 4,
5, 6) - count
- shapeArray3 new Circle(4, 5, 6)
- count
- shapeArray4 new Rectangle(1, 2, 3,
4) - count
- shapeArray5 new Triangle(7, 8, 9, 10,
11, 12) -
- for(int i0 iltcount i)
- System.out.print("Element " (i1)
" ")
17Copying Arrays
previous start next
- Copying an array reference yields a second
reference to the same array double data
new double10 // fill array . . . double
prices data
previous start next
18 - Use clone to make true copydouble prices
(double)data.clone()
19Copying Array Elements
- System.arraycopy(from, fromStart, to, toStart,
count)
20Adding and Removing Array Elements
- Add an elementSystem.arraycopy(data, i, data,
i 1, data.length - i - 1)datai x
21- Remove an element System.arraycopy(data, i
1, data, i, data.length - i - 1)
22Partially Filled Arrays
- Array length maximum number of elements in
array - Usually, array is partially filled
- Need companion variable to keep track of current
size - Uniform naming convention final int
DATA_LENGTH 100 double data new
doubleDATA_LENGTH int dataSize 0 - Update dataSize as array is filled datadataSiz
e x dataSize
23Partially Filled Arrays
24Partially Filled Arrays
- Remember to stop at dataSize when looking at
array elementsfor (int i 0 i lt dataSize
i) sum sum datai - Be careful not to overfill the arrayif (dataSize
gt data.length) System.out.println("Sorry--arra
y full") - Grow the arraydouble newData new double2
data.lengthSystem.arraycopy(data, 0, newData,
0, data.length)data newData
25Growing an Array
26Maximum Length Current Size
- (maximum) length number of elements is also
known as - Capacity, maximum size, maximum number of
elements - Current size is also known as
- size, number of elements
27DataSet.java
- public class DataSet
- private double data
- private int dataSize
-
- public DataSet()
- final int DATA_LENGTH 100
- data new doubleDATA_LENGTH
- dataSize 0
- // DataSet()
- public void add(double x)
- if (dataSize gt data.length)
- double newData new double2
data.length -
- System.arraycopy(data, 0, newData, 0,
data.length) - data newData
-
-
- datadataSize x
28DataSet.java
- public double getAverage()
- double sum 0
- for (int i 0 i lt dataSize i)
- sum sum datai
-
-
- return sum / dataSize
- // getAverage()
- // DataSet
29DataSetTest.java
- import java.util.Random
- public class DataSetTest
- public static void main(String args)
- Random generator new Random()
- DataSet data new DataSet()
- final int COUNT 10000
-
- System.out.println("Adding " COUNT "
random numbers.") -
- for (int i 0 i lt COUNT i)
- double x generator.nextDouble()
- data.add(x)
-
-
- double average data.getAverage()
- System.out.println("average" average)
-
- // DataSetTest
30Vector
- Consider Purse class
- Purse doesn't remember individual Coin objects,
just the total - Don't know how many coins--can't have variables
coin1...coin10 - Use Vector to store variable number of
objectsVector coins new Vector()coins.add(new
Coin(0.1, "dime")). . . - size method yields number of elements
31Retrieving Vector Elements
- Use get method
- Index still starts at 0
- Must cast to correct type
- Coin c coins.get(0) // gets first coin
- Bounds error if index is out of range
- Most common bounds errorint n coins.size()c
(Coin)coins.get(n) // ERROR // legal index
values are 0...n-1
32(No Transcript)
33Array of Objects
- class ShapeArrayDemo
- public ShapeArrayDemo()
- Shape shapeArray new Shape100
- int count 0
-
- shapeArray0 new Circle(1, 2, 3)
- count
- shapeArray1 new Rectangle(1, 2, 3,
4) - count
- shapeArray2 new Triangle(1, 2, 3, 4,
5, 6) - count
- shapeArray3 new Circle(4, 5, 6)
- count
- shapeArray4 new Rectangle(1, 2, 3,
4) - count
- shapeArray5 new Triangle(7, 8, 9, 10,
11, 12) -
- for(int i0 iltcount i)
- System.out.print("Element " (i1)
" ")
34Vector of Objects
- class ShapeVectorDemo
- public ShapeVectorDemo()
- Vector shapeVector new Vector()
-
- shapeVector.add(new Circle(1, 2, 3))
- shapeVector.add(new Rectangle(1, 2, 3,
4)) - shapeVector.add(new Triangle(1, 2, 3, 4,
5, 6)) - shapeVector.add(new Circle(4, 5, 6))
- shapeVector.add(new Rectangle(1, 2, 3,
4)) - shapeVector.add(new Triangle(7, 8, 9, 10,
11, 12)) -
- for(int i0 iltshapeVector.size() i)
- System.out.print("Element " (i1)
" ") - System.out.println((shapeVector.get(i)
).toString()) - System.out.print("Area is "
((Shape) shapeVector.get(i)).getArea()) - System.out.println("Circumference "
((Shape) shapeVector.get(i)).getCircumference())
-
- // ShapeVectorDemo()
- // ShapeVectorDemo
35Stepping Through all Elements
- for (int i 0 i lt coins.size( ) i) Coin c
(Coin)coins.get(i) // do something with c
36Adding and Removing Elements
- set overwrites an existing value coins.set(4,
aNickel) - add adds a new value before the value at index
add(i, c)
37- remove removes an element at an index
38File Coin.java
- public class Coin
- private double value
- private String name
-
- public Coin(double aValue, String aName)
- value aValue
- name aName
- // Coin
- public double getValue()
- return value
- // getValue
- public String getName()
- return name
- // getName
- public boolean equals(Object otherObject)
- Coin other (Coin)otherObject
39File Purse.java
- import java.util.Vector
- public class Purse
- private Vector coins
- public Purse()
- coins new Vector()
-
- public void add(Coin aCoin)
- coins.add(aCoin)
-
- public double getTotal()
- double total 0
- for (int i 0 i lt coins.size() i)
- Coin aCoin (Coin) coins.get(i)
- total total aCoin.getValue()
-
40Linear Search Algorithm
- // public class Purse
- public boolean find(Coin aCoin)
- boolean found false
-
- for (int i 0 (i lt coins.size())
(foundfalse) i) - Coin c (Coin)coins.get(i)
- found c.equals(aCoin)
-
-
- return found
- // find()
41Counting
- // public class Purse
- public int count(Coin aCoin)
- int matches 0
-
- for (int i 0 i lt coins.size() i)
- Coin c (Coin)coins.get(i)
- if (c.equals(aCoin))
- matches
-
- // for
-
- return matches
- // count()
42Finding Maximum
- // public class Purse
- public Coin getMaximum()
- Coin max (Coin)coins.get(0)
-
- for (int i 1 i ltcoins.size() i)
- Coin c (Coin)coins.get(i)
- if (c.getValue()gtmax.getValue())
- max c
-
-
- return max
-
- // Purse
43File Purse.java
- import java.util.Vector
- public class Purse
- private Vector coins
-
- public Purse()
- coins new Vector()
-
- public void add(Coin aCoin)
- coins.add(aCoin)
-
- public double getTotal()
- double total 0
-
- for (int i 0 i lt coins.size() i)
- Coin aCoin (Coin) coins.get(i)
- total total aCoin.getValue()
44File Purse.java
- public int count()
- return coins.size()
-
- public boolean find(Coin aCoin)
- boolean found false
-
- for (int i 0 (i lt coins.size())
(found false) i) - Coin c (Coin)coins.get(i)
- found c.equals(aCoin)
-
-
- return found
- // find()
45File Purse.java
- public int count(Coin aCoin)
- int matcheCount 0
-
- for (int i 0 i lt coins.size() i)
- Coin c (Coin)coins.get(i)
-
- if (c.equals(aCoin))
- matcheCount
-
-
-
- return matcheCount
- // count()
46File Purse.java
- public Coin getMaximum()
- Coin max (Coin) coins.get(0)
-
- for (int i 1 i lt coins.size() i)
- Coin c (Coin)coins.get(i)
-
- if (c.getValue() gt max.getValue())
- max c
-
-
-
- return max
- // getMaximum()
- // Purse
47Storing Numbers in a Vector
- Array lists vectors store objects, never
primitives - Use wrapper classes to store numbers
- Double wrapper new Double(29.95)double
unwrapped wrapper.doubleValue() - Vector data new Vector()data.add(wrapper)unw
rapped ((Double).data.get(i)).doubleValue() - Also have Integer and Boolean wrappers
48Two-Dimensional Arrays
- Matrix with rows and columns
- Example Tic Tac Toe board
char board new char33boardij
'x'
49TicTacToe.java
- public class TicTacToe
- private char board
- private static final int ROWS 3
- private static final int COLUMNS 3
-
- public TicTacToe()
- board new charROWSCOLUMNS
- // fill with spaces
- for (int i 0 i lt ROWS i)
- for (int j 0 j lt COLUMNS j)
- boardij ' '
-
-
- // TicTacToe()
- public void set(int i, int j, char player)
-
- if (boardij ! ' ')
50TicTacToe.java
- /
- Creates a string representation of the
board such as - x o
- x
- o
- _at_return the string representation
- /
- public String toString()
- String r ""
-
- for (int i 0 i lt ROWS i)
- r r ""
-
- for (int j 0 j lt COLUMNS j)
- r r boardij
-
- r r "\n"
- // for
-
51TicTacToeTest.java
- import javax.swing.JOptionPane
- public class TicTacToeTest
- public static void main(String args)
- char player X', 'O'
- int turn 0 // set turn to x
- TicTacToe game new TicTacToe()
- String input "new game" // set to non
null -
- while (input ! null)
- System.out.println(game) // calls
game.toString() - input JOptionPane.showInputDialog(
"Row for " playerturn -
" (Cancel to
exit)") - if (input ! null)
- int row Integer.parseInt(input)
- input JOptionPane.showInputDialog("Co
lumn for " playerturn) - int column Integer.parseInt(input)
- game.set(row, column, playerturn)
-
52Summary you should now
- Be familiar with using vectors to store a
collection of objects - Know about common array algorithms
- Be able to use arrays
- Understand when to choose vectors versus arrays
in your programs - Be able to implement partially filled arrays
- Know how to use two-dimensional arrays
53Chapter 13 Key Terms Concepts
- Array (in general)
- Java primitive array
- Element
- Index, subscript
- Partially filled array
- Vector (the class)
- Bound errors
- Comparing array
- element type (class)
- Adding an element
- Removing an element
- Setting an element to a value
- Searching for an element
- Sorting elements
- Ways to copy an array
- Two-dimensional arrays
- Wrapper classes
- Current size, size, number of elements
- (maximum length), capacity
- Watch out for the meaning of length
54Questions?