Title: Arrays and Vectors
1Chapter 11
Arrays and Vectors
2Print all prices, mark the lowest
- 19.9523.9524.9518.95 lt- lowest
price29.9519.9520.0022.9924.9519.95
3Variable number of values
- Can't just have variables data1, data2, ...,
data10 - Code would be tedious
- What if we have 1000 numbers?
- Array collection of values of the same type
- double data new double10
4Figure 1 An Array Reference and an Array
5Accessing array elements
- Index (or subscript) operator data4
29.95System.out.println(data4) - Unpleasant detail data4 is the fifth value in
the array - data0 the first valuedata1 the second
value. . .data9 the tenth value
6Figure 2 Filling an Array Element
7Common Errors
- Bounds errorint i 20System.out.println(datai
) - Most common form double datanew
double20data20 19.95 - Forgot to initializedouble datadata0
19.95
8Array length
- Public instance variable length yields number of
elements in array, e.g. a.length - Read-only. Can't assign to a.length
- Most common use for (int i 0 i lt a.length
i) do something with ai - Asymmetric bounds 0 i lt a.lengthDon't use
for (int i 0 i lt a.length - 1 i)
9Copying Arrays
- Array variables are referencesdouble datanew
double10double prices dataNow both
variables point to the same array - data0 19.95Now both data0 and prices0
are 19.95
10Figure 3 Copying an Array Reference
11Copying all values of an array
- Explicit loopdouble prices new
doubledata.lengthfor (int i 0 i lt
data.length i) pricesi datai - Use System.arraycopySystem.arraycopy(data, 0,
prices, 0, data.length)
12Figure 4 The System.arrayCopy Method
13Partially Filled Arrays
- Problem Don't know how many data values are in
the input set - Remedy Make the array larger than the largest
data set, remember how much is filled - final int DATA_LENGTH 1000double data new
doubleDATA_LENGTHint dataSize 0 - Fill in values and increment size datadataSize
new valuedataSize
14Figure 5 Size of a Partially Filled Array
15Partially Filled Arrays
- Use the _LENGTH, Size naming convention!
- What if the array fills up? Can refuse additional
entriesif (dataSize gt DATA_LENGTH)
System.out.println("Sorry") - Can grow arraydouble newDatanew
double2data.lengthSystem.arrayCopy(data,0,new
Data,0, data.length)data newData
16Figure 6 Growing a Dynamic Array
17Program BestPrice.java public class BestPrice
public static void main(String args)
final int DATA_LENGTH 1000 double data
new doubleDATA_LENGTH int dataSize
0 // read data ConsoleReader
console new ConsoleReader(System.in)
boolean done false while (!done)
System.out.println("Enter price, 0 to quit")
double price console.readDouble()
if (price 0) // end of input
done true
18 else if (dataSize lt data.length) // add
price to data array datadataSize
price dataSize else // array is
full System.out.println("Sorry, the array
is full.") done true // compute
lowest price if (dataSize 0) return // no
data double lowest data0 for (int i 1 i lt
dataSize i) if (datai lt lowest) lowest
datai // print out prices, marking the lowest
one
19 for (int i 0 i lt dataSize i)
System.out.print(datai) if (datai
lowest) System.out.print(
lt--lowest price") System.out.println()
20Array Parameters
- static double average(double data) if
(data.length 0) return 0 double sum 0
for (int i 0 i lt data.length i) sum
sum datai return sum / n - Call asdouble prices new double20. .
.double avg average(prices)
21Figure 7 Passing an Array to a Method
22Returning an Array
- Construct an array with random test datastatic
int randomData(int length, int n) Random
generator new Random() int data new
intlength for (int i 0 i lt data.length
i) datai generator.nextInt(n)
return data - Call asint data randomData(length, n)
23Common algorithms find value
- double prices . . .double targetPrice
1000int i 0boolean found falsewhile (i
lt prices.length !found) if (prices i lt
targetPrice) found true else
iif (found) System.out.println("Item "
i " has a price of " pricesi)
24Common algorithms count values
- double prices . . .double targetPrice
1000int count 0for(i 0 i lt
prices.length i) if (prices i lt
targetPrice) countSystem.out.println(c
ount " matches")
25Figure 8 Removing an Element from an Array
26Program Remove1.java public class Remove1
public static void main(String args)
ConsoleReader console new ConsoleReader(System.i
n) String staff new String5
staff0 "Harry" staff1 "Romeo" staff2
"Dick" staff3 "Juliet" staff4
"Tom" int staffSize staff.length print(staff,
staffSize) System.out.println("Remove which
element? (0 - 4)") int pos console.readInt()
27 // overwrite the removed element with the
last element staffpos staffstaffSize
- 1 staffSize--
print(staff,staffSize) / Prints
an array of strings _at_param s the string
array _at_param sSize the number of strings in
the array / public static void
print(String s, int sSize) for (int i
0 i lt sSize i) System.out.println(i
" si)
28Figure 9 Removing an Element from an Ordered
Array Element
29Program Remove2.java public class Remove2
public static void main(String args)
ConsoleReader console new ConsoleReader(System.i
n)
String staff new String5 staff0
"Dick" staff1 "Harry" staff2
"Juliet" staff3 "Romeo" staff4
"Tom" int staffSize staff.length print(staff,
staffSize) System.out.println("Remove which
element? (0 - 4)") int pos console.readInt() /
/ shift all elements above pos down
30 for (int i pos i lt staffSize - 1 i)
staffi staffi 1
staffSize-- print(staff, staffSize)
/ Prints an array of strings
_at_param s the string array _at_param sSize the
number of strings in the array / public
static void print(String s, int sSize)
for (int i 0 i lt sSize i)
System.out.println(i " si)
31Figure 10 Inserting an Element in an Ordered Array
32Program Insert.java public class Insert
public static void main(String args)
ConsoleReader console new ConsoleReader(System.i
n) String staff new String6
staff0 "Dick" staff1 "Harry"
staff2 "Juliet" staff3 "Romeo"
staff4 "Tom" int staffSize
staff.length - 1 print(staff,
staffSize) System.out.print
("Insert before which element? (0 - 4)")
int pos console.readInt()
33 // shift all element after pos up by one
for (int i staffSize i gt pos i--)
staffi staffi - 1 // insert new
element into freed slot staffpos "New,
Nina" staffSize print(staff,
staffSize)
34 / Prints an array of strings
_at_param s the string array _at_param sSize the
number of strings in the array / public
static void print(String s, int sSize)
for (int i 0 i lt sSize i)
System.out.println(i " si)
35Parallel Arrays
- Product dataAceAcro 740 3499.0 score 71ACMA
P500 3195.0 score 64Maximus 2495.0
score 72lt-best buySummit 2995.0 score
48 - Naive solution 3 parallel arraysString
namesdouble pricesint scores
36Figure 11 Parallel Arrays
37Program BestData.java public class BestData
public static void main(String args)
final int DATA_LENGTH 1000 String
names new StringDATA_LENGTH double
prices new doubleDATA_LENGTH int
scores new intDATA_LENGTH int
dataSize 0 // read data
ConsoleReader console new ConsoleReader(System.i
n)
38boolean done false while (!done)
System.out.println ("Enter name or leave
blank when done") String inputLine
console.readLine() if (inputLine null
inputLine.equals("")) done true else
if (dataSize lt DATA_LENGTH)
namesdataSize inputLine
System.out.println("Enter price")
inputLine console.readLine()
pricesdataSize Double.parseDouble(inputLine)
System.out.println("Enter score")
inputLine console.readLine()
scoresdataSize Integer.parseInt(inputLine)
dataSize
39 else // array is full System.out.println(
"Sorry, the array is full.") done true
// compute best buy if (dataSize 0)
return // no data double best scores0 /
prices0 for (int i 1 i lt dataSize i)
if (scoresi / pricesi gt best) best
scoresi / pricesi // print out products,
marking the best buys final int COLUMN_WIDTH
30
40for (int i 0 i lt dataSize i)
System.out.print(namesi) // pad with
spaces to fill column int pad COLUMN_WIDTH
- namesi.length() for (int j 1 j lt pad
j) System.out.print( ") // print
price and score System.out.print(
pricesi score scoresi)
41 // mark if best buy if
(scoresi / pricesi best)
System.out.print( lt-- best buy")
System.out.println()
42Eliminating parallel arrays
- Parallel arrays are an indication of a missed
opportunity for finding objects - class Product . . . private String name
private double price private int score - Product products
43Figure 12 Eliminating Parallel Arrays
44Program BestProduct.java public class
BestProduct public static void main(String
args) final int DATA_LENGTH 1000
Product data new ProductDATA_LENGTH
int dataSize 0 // read data
ConsoleReader console new ConsoleReader(System.i
n) boolean done false while
(!done) Product p readProduct(console)
if (p null) done true
45 else if (dataSize lt DATA_LENGTH)
datadataSize p dataSize
else // array is full System.out.println("So
rry, the array is full.") done true
// compute best buy if (dataSize 0)
return // no data double best
data0.getScore() / data0.getPrice()
46 for (int i 1 i lt dataSize i)
double ratio datai.getScore() /
datai.getPrice() if (ratio gt best)
best ratio // print out data,
marking the best buys for (int i 0 i lt
dataSize i) printProduct(datai)
if (datai.getScore() / datai.getPrice()
best) System.out.print( lt-- best
buy") System.out.println()
47/ Reads a product from a console reader.
_at_param in the reader _at_return the product read
if a product was successfully read, null if
end of input was detected / public static
Product readProduct(ConsoleReader in)
System.out.println ("Enter name or leave
blank when done") String name
in.readLine() if (name null
name.equals("")) return null
System.out.println("Enter price") String
inputLine in.readLine() double price
Double.parseDouble(inputLine)
System.out.println("Enter score") inputLine
in.readLine() int score
Integer.parseInt(inputLine) return new
Product(name, price, score)
48 / Prints a product description.
_at_param p the product to print / public
static void printProduct(Product p) final
int COLUMN_WIDTH 30 System.out.print(p.g
etName()) // pad with spaces to fill
column int pad COLUMN_WIDTH -
p.getName().length() for (int i 1 i lt
pad i) System.out.print( ")
System.out.print( p.getPrice()
score p.getScore())
49Arrays of Objects
- public class Polygon public Polygon(int n)
corners new Point2D.Doublen
cornersSize 0 public void add(int
i,Point2D.Double p) if (cornersSize lt
corners.length) cornerscornersSize
p cornersSize public
void draw(Graphics2D g2) ... private
Point2D.Double corners - x
50Figure 13 A Polygon
51Arrays of objects
- cornersnew Point2D.Doublencreates an array of
null references - Need to set each of them to an objectcornerscor
nersSize p - Polygon examplePolygon triangle new
Polygon(3)triangle.add(new Point2D.Double(40,40)
)triangle.add(new Point2D.Double(120,160))tria
ngle.add(new Point2D.Double(20,120))
52Arrays of objects
- draw methodpublic void draw(Graphics2D g2)
for (int i 0 i lt cornersSize i)
Point2D.Double from cornersi
Point2D.Double to corners(i 1)
cornersSize g2.draw(new
Line2D.Double(from, to)) - Why not juststatic void drawPolygon(Graphics2D
g2, Point2D.Double a)
53Figure 14 The Output of the PolygonTest program
54Program PolygonTest.java import
java.applet.Applet import java.awt.Graphics
import java.awt.Graphics2D import
java.awt.geom.Line2D import java.awt.geom.Point2D
public class PolygonTest extends Applet
public void paint(Graphics g) Graphics2D g2
(Graphics2D)g Polygon triangle new
Polygon(3) triangle.add(new
Point2D.Double(40, 40)) triangle.add(new
Point2D.Double(120, 160)) triangle.add(new
Point2D.Double(20, 120))
55 double x 200 double y 200
double r 50 Polygon pentagon new
Polygon(5) for (int i 0 i lt 5 i)
pentagon.add(new Point2D.Double(
x r Math.cos(2 Math.PI i / 5),
y r Math.sin(2 Math.PI I / 5)))
triangle.draw(g2) pentagon.draw(g2)
/ A polygon is a closed curve made up
from line segment that join the corner
points. /
56class Polygon / Constructs a polygon
with a given number of corner points.
_at_param n the number of corner points. /
public Polygon(int n) corners new
Point2D.Doublen cornersSize 0
/ Adds a corner point of the polygon.
The point is ignored if the maximum number
of points has been added. _at_param p the
corner point / public void
add(Point2D.Double p) if (cornersSize lt
corners.length)
57 cornerscornersSize p
cornersSize / Draws the polygon.
_at_param g2 the graphics context / public void
draw(Graphics2D g2) for (int i 0 i lt
cornersSize i) Point2D.Double from
cornersi Point2D.Double to
corners(i 1) corners.length
g2.draw(new Line2D.Double(from, to))
58 private Point2D.Double corners private
int cornersSize
59Program CloudTest.java import java.applet.Applet
import java.awt.Graphics import
java.awt.Graphics2D import java.awt.geom.Ellipse2
D import java.awt.geom.Point2D import
java.util.Random public class CloudTest
extends Applet public void paint(Graphics g)
Graphics2D g2 (Graphics2D)g Random
generator new Random() final int
CLOUD_SIZE 100 Cloud randomCloud new
Cloud(CLOUD_SIZE) for (int i 0 i lt
CLOUD_SIZE i) // generate two random
numbers between 100 and 200
60 double x 100 100
generator.nextDouble() double y 100
100 generator.nextDouble()
randomCloud.add(new Point2D.Double(x, y))
randomCloud.draw(g2) / A
cloud is a collection of dots. / class Cloud
/ Constructs a cloud with a given number
of dots. _at_param n the number of dots. /
61public Cloud(int n) dots new
Point2D.Doublen dotsSize 0 /
Sets a dot point of the cloud. The point is
ignored if the maximum number of points has been
added. _at_param p the dot point / public void
add(Point2D.Double p) if (dotsSize lt
dots.length) dotsdotsSize p
dotsSize / Draws the cloud.
_at_param g2 the graphics context /
62 public void draw(Graphics2D g2) final
double SMALL_CIRCLE_RADIUS 2 for (int i
0 i lt dotsSize i) Ellipse2D.Double
smallCircle new Ellipse2D.Double(
dotsi.getX() - SMALL_CIRCLE_RADIUS,
dotsi.getY() - SMALL_CIRCLE_RADIUS,
2 SMALL_CIRCLE_RADIUS, 2
SMALL_CIRCLE_RADIUS)
g2.draw(smallCircle) private
Point2D.Double dots private int dotsSize
63Figure 15 The Output of the CloudTest Program
64Vectors
- Dynamically growing array of objectsVector
products new Vector() - No need to set length. Can add as many elements
as desiredProduct p . . .products.add(p) - Overwrite existing elementproducts.set(i, p)
65Vectors
- Get current sizefor (i0 iltproducts.size()
i) - Must use cast to get elementsProduct p
(Product)products.get(i) - Must wrap numbers into wrapper classesdata.add(ne
w Double(3.14))x ((Double)data.get(i)).doubleV
alue() - Can copy into array (after growing
stops)Product a new Productv.size()v.copy
Into(a)
66Program Table2.java public class Table2
public static void main(String args)
final int COLUMN_WIDTH 10 int powers
new int108 for (int i 0 i lt
powers.length i) for (int j 0 j lt
powersi.length j) powersij
(int)Math.pow(i 1, j 1)
printTable(powers, COLUMN_WIDTH) /
Prints a two-dimensional array of integers
_at_param table the values to be printed _at_param
width the column width /
672D Arrays
- Store table of powers xy 1 1 1 1 1 2
4 8 16 32 3 9 27 81 243 . . . - int powers new introwscolumns
- powers34 Math.pow(3, 4)
68public static void printTable(int table, int
width) for (int i 0 i lt table.length i)
for (int j 0 j lt tablei.length j)
System.out.print(format(tableij,
width)) System.out.println()
/ Formats an integer to fit in a field
of constant width. _at_param n the integer to
format _at_param width the field width _at_return
a string of length width, consisting of
leading spaces followed by the number n /
69 public static String format(int n, int width)
String nstr " n // pad with
spaces while (nstr.length() lt width)
nstr nstr return nstr
70Figure 16 A Two-Dimensional Array
71Figure 17 Glider
72Figure 18 Glider Gun