Download Chapter 11

Document related concepts
no text concepts found
Transcript
1
Chapter 11: Arrays and Vectors
Chapter 11
Arrays and Vectors
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
2
Chapter 11: Arrays and Vectors
Print all prices, mark the lowest
• 19.95
23.95
24.95
18.95 <- lowest price
29.95
19.95
20.00
22.99
24.95
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
19.95
3
Chapter 11: Arrays and Vectors
Variable 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 double[10];
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
4
Chapter 11: Arrays and Vectors
Figure 1
An Array Reference and an
Array
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
5
Chapter 11: Arrays and Vectors
Accessing array elements
• Index (or subscript) operator
data[4] = 29.95;
System.out.println(data[4]);
• Unpleasant detail: data[4] is the fifth
value in the array
• data[0] = the first value
data[1] = the second value
...
©2000,
John Wiley
& Sons, Inc.
data[9] = the
tenth
value
Horstmann/Java Essentials, 2/e
6
Chapter 11: Arrays and Vectors
Figure 2
Filling an Array
Element
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
7
Chapter 11: Arrays and Vectors
Common Errors
• Bounds error
int i = 20;
System.out.println(data[i]);
• Most common form:
double[] data=new double[20];
data[20] = 19.95;
• Forgot to initialize:
double[] data;
John Wiley & Sons, Inc.
data[0] = ©2000,
19.95;
Horstmann/Java Essentials, 2/e
8
Chapter 11: Arrays and Vectors
Array 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 < a.length; i++)
do something with a[i]
• Asymmetric bounds: 0  i < a.length
Don't use
for (int i = 0; i <= a.length - 1; i++)
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
9
Chapter 11: Arrays and Vectors
Copying Arrays
• Array variables are references:
double[] data=new double[10];
double[] prices = data;
Now both variables point to the same array
• data[0] = 19.95;
Now both data[0] and prices[0] are
19.95
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
10
Chapter 11: Arrays and Vectors
Figure 3
Copying an Array
Reference
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
11
Chapter 11: Arrays and Vectors
Copying all values of an array
• Explicit loop:
double[] prices
= new double[data.length];
for (int i = 0; i < data.length; i++)
prices[i] = data[i];
• Use System.arraycopy
System.arraycopy(data, 0, prices, 0,
data.length);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
12
Chapter 11: Arrays and Vectors
Figure 4
The System.arrayCopy
Method
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
13
Chapter 11: Arrays and Vectors
Partially 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 = 1000;
double[] data = new double[DATA_LENGTH];
int dataSize = 0;
• Fill in values and increment size
data[dataSize] = new value;
dataSize++; ©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
14
Chapter 11: Arrays and Vectors
Figure 5
Size of a Partially Filled Array
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
15
Chapter 11: Arrays and Vectors
Partially Filled Arrays
• Use the _LENGTH, Size naming convention!
• What if the array fills up? Can refuse additional
entries:
if (dataSize >= DATA_LENGTH)
System.out.println("Sorry");
• Can grow array:
double[] newData=new double[2*data.length];
System.arrayCopy(data,0,newData,0,
data.length);
data = newData;
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
16
Chapter 11: Arrays and Vectors
Figure 6
Growing a Dynamic Array
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
17
Chapter 11: Arrays and Vectors
Program BestPrice.java
public class BestPrice
{ public static void main(String[] args)
{ final int DATA_LENGTH = 1000;
double[] data = new double[DATA_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;
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
18
Chapter 11: Arrays and Vectors
else if (dataSize < data.length)
{ // add price to data array
data[dataSize] = 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 = data[0];
for (int i = 1; i < dataSize; i++)
if (data[i] < lowest) lowest = data[i];
// print out prices, marking the lowest one
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
19
Chapter 11: Arrays and Vectors
for (int i = 0; i < dataSize; i++)
{ System.out.print(data[i]);
if (data[i] == lowest)
System.out.print(” <--lowest price");
System.out.println();
}
}
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
20
Chapter 11: Arrays and Vectors
Array Parameters
•
static double average(double[] data)
{ if (data.length == 0) return 0;
double sum = 0;
for (int i = 0; i < data.length; i++)
sum = sum + data[i];
return sum / n;
}
• Call as
double[] prices = new double[20];
. . .
double avg = average(prices);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
21
Chapter 11: Arrays and Vectors
Figure 7
Passing an Array to a Method
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
22
Chapter 11: Arrays and Vectors
Returning an Array
• Construct an array with random test data
static int[] randomData(int length,
int n)
{ Random generator = new Random();
int[] data = new int[length];
for (int i = 0; i < data.length; i++)
data[i] = generator.nextInt(n);
return data;
}
• Call as
int[] data = randomData(length, n);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
23
Chapter 11: Arrays and Vectors
Common algorithms: find value
•
double[] prices = . . .;
double targetPrice = 1000;
int i = 0;
boolean found = false;
while (i < prices.length && !found)
{ if (prices [i] <= targetPrice)
found = true;
else
i++;
}
if (found)
System.out.println("Item " + i +
John Wiley
& Sons,
" has a©2000,
price
of
" Inc.+ prices[i]);
Horstmann/Java Essentials, 2/e
24
Chapter 11: Arrays and Vectors
Common algorithms: count values
•
double[] prices = . . .;
double targetPrice = 1000;
int count = 0;
for(i = 0; i < prices.length; i++)
{ if (prices [i] <= targetPrice)
count++;
}
System.out.println(count + " matches");
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
25
Chapter 11: Arrays and Vectors
Figure 8
Removing an Element
from an Array
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
26
Chapter 11: Arrays and Vectors
Program Remove1.java
public class Remove1
{ public static void main(String[] args)
{ ConsoleReader console = new ConsoleReader(System.in);
String[] staff = new String[5];
staff[0] = "Harry";
staff[1] = "Romeo";
staff[2] = "Dick";
staff[3] = "Juliet";
staff[4] = "Tom";
int staffSize = staff.length;
print(staff, staffSize);
System.out.println("Remove which element? (0 - 4)");
int pos = console.readInt();
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
27
Chapter 11: Arrays and Vectors
// overwrite the removed element with the last element
staff[pos] = staff[staffSize - 1];
staffSize--;
print(staff,staffSize);
}
/**
Prints an array of strings
@param s the string array
@param sSize the number of strings in the array
*/
public static void print(String[] s, int sSize)
{ for (int i = 0; i < sSize; i++)
System.out.println(i + ": ” + s[i]);
}
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
28
Chapter 11: Arrays and Vectors
Figure 9
Removing an Element
from an
Ordered Array
Element
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
29
Chapter 11: Arrays and Vectors
Program Remove2.java
public class Remove2
{ public static void main(String[] args)
{ ConsoleReader console = new ConsoleReader(System.in);
String[] staff = new String[5];
staff[0] = "Dick";
staff[1] = "Harry";
staff[2] = "Juliet";
staff[3] = "Romeo";
staff[4] = "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
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
30
Chapter 11: Arrays and Vectors
for (int i = pos; i < staffSize - 1; i++)
staff[i] = staff[i + 1];
staffSize--;
print(staff, staffSize);
}
/**
Prints an array of strings
@param s the string array
@param sSize the number of strings in the array
*/
public static void print(String[] s, int sSize)
{ for (int i = 0; i < sSize; i++)
System.out.println(i + ": ” + s[i]);
}
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
31
Chapter 11: Arrays and Vectors
Figure 10
Inserting an Element in
an Ordered Array
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
32
Chapter 11: Arrays and Vectors
Program Insert.java
public class Insert
{ public static void main(String[] args)
{ ConsoleReader console = new ConsoleReader(System.in);
String[] staff = new String[6];
staff[0] = "Dick";
staff[1] = "Harry";
staff[2] = "Juliet";
staff[3] = "Romeo";
staff[4] = "Tom";
int staffSize = staff.length - 1;
print(staff, staffSize);
System.out.print
("Insert before which element? (0 - 4)");
int pos = console.readInt();
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
33
Chapter 11: Arrays and Vectors
// shift all element after pos up by one
for (int i = staffSize; i > pos; i--)
staff[i] = staff[i - 1];
// insert new element into freed slot
staff[pos] = "New, Nina";
staffSize++;
print(staff, staffSize);
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
34
Chapter 11: Arrays and Vectors
/**
Prints an array of strings
@param s the string array
@param sSize the number of strings in the array
*/
public static void print(String[] s, int sSize)
{ for (int i = 0; i < sSize; i++)
System.out.println(i + ": ” + s[i]);
}
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
35
Chapter 11: Arrays and Vectors
Parallel Arrays
• Product data
AceAcro 740
ACMA P500
Maximus
Summit
$3499.0
$3195.0
$2495.0
$2995.0
score
score
score
score
=
=
=
=
71
64
72<-best buy
48
• Naive solution: 3 “parallel” arrays
String[] names;
double[] prices;
int[] scores;
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
36
Chapter 11: Arrays and Vectors
Figure 11
Parallel Arrays
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
37
Chapter 11: Arrays and Vectors
Program BestData.java
public class BestData
{ public static void main(String[] args)
{ final int DATA_LENGTH = 1000;
String[] names = new String[DATA_LENGTH];
double[] prices = new double[DATA_LENGTH];
int[] scores = new int[DATA_LENGTH];
int dataSize = 0;
// read data
ConsoleReader console = new ConsoleReader(System.in);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
38
Chapter 11: Arrays and Vectors
boolean 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 < DATA_LENGTH)
{
names[dataSize] = inputLine;
System.out.println("Enter price:");
inputLine = console.readLine();
prices[dataSize] = Double.parseDouble(inputLine);
System.out.println("Enter score:");
inputLine = console.readLine();
scores[dataSize] = Integer.parseInt(inputLine);
dataSize++;
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
39
Chapter 11: Arrays and Vectors
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 = scores[0] / prices[0];
for (int i = 1; i < dataSize; i++)
if (scores[i] / prices[i] > best)
best = scores[i] / prices[i];
// print out products, marking the best buys
final int COLUMN_WIDTH = 30;
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
40
Chapter 11: Arrays and Vectors
for (int i = 0; i < dataSize; i++)
{ System.out.print(names[i]);
// pad with spaces to fill column
int pad = COLUMN_WIDTH - names[i].length();
for (int j = 1; j <= pad; j++)
System.out.print(” ");
// print price and score
System.out.print(” $” + prices[i]
+ ” score = ” + scores[i]);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
41
Chapter 11: Arrays and Vectors
// mark if best buy
if (scores[i] / prices[i] == best)
System.out.print(” <-- best buy");
System.out.println();
}
}
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
42
Chapter 11: Arrays and Vectors
Eliminating 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;
}
John Wiley & Sons, Inc.
• Product[] ©2000,
products
Horstmann/Java Essentials, 2/e
43
Chapter 11: Arrays and Vectors
Figure 12
Eliminating Parallel Arrays
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
44
Chapter 11: Arrays and Vectors
Program BestProduct.java
public class BestProduct
{ public static void main(String[] args)
{ final int DATA_LENGTH = 1000;
Product[] data = new Product[DATA_LENGTH];
int dataSize = 0;
// read data
ConsoleReader console = new ConsoleReader(System.in);
boolean done = false;
while (!done)
{ Product p = readProduct(console);
if (p == null)
done = true;
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
45
Chapter 11: Arrays and Vectors
else if (dataSize < DATA_LENGTH)
{ data[dataSize] = p;
dataSize++;
}
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
= data[0].getScore() / data[0].getPrice();
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
46
Chapter 11: Arrays and Vectors
for (int i = 1; i < dataSize; i++)
{ double ratio
= data[i].getScore() / data[i].getPrice();
if (ratio > best)
best = ratio;
}
// print out data, marking the best buys
for (int i = 0; i < dataSize; i++)
{ printProduct(data[i]);
if (data[i].getScore() / data[i].getPrice() == best)
System.out.print(” <-- best buy");
System.out.println();
}
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
47
Chapter 11: Arrays and Vectors
/**
Reads a product from a console reader.
@param in the reader
@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);
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
48
Chapter 11: Arrays and Vectors
/**
Prints a product description.
@param p the product to print
*/
public static void printProduct(Product p)
{ final int COLUMN_WIDTH = 30;
System.out.print(p.getName());
// pad with spaces to fill column
int pad = COLUMN_WIDTH - p.getName().length();
for (int i = 1; i <= pad; i++)
System.out.print(” ");
System.out.print(” $” + p.getPrice()
+ ” score = ” + p.getScore());
}
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
49
Chapter 11: Arrays and Vectors
Arrays of Objects
•
public class Polygon
{ public Polygon(int n)
{ corners = new Point2D.Double[n];
cornersSize = 0;
}
public void add(int i,Point2D.Double p)
{ if (cornersSize < corners.length)
{ corners[cornersSize] = p;
cornersSize++;
}
}
public void draw(Graphics2D g2) {...}
private Point2D.Double[]
corners;
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
}
50
Chapter 11: Arrays and Vectors
Figure 13
A Polygon
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
51
Chapter 11: Arrays and Vectors
Arrays of objects
• corners=new Point2D.Double[n]
creates an array of null references
• Need to set each of them to an object:
corners[cornersSize] = p;
• Polygon example:
Polygon triangle
triangle.add(new
triangle.add(new
triangle.add(new
= new Polygon(3);
Point2D.Double(40,40));
Point2D.Double(120,160));
Point2D.Double(20,120));
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
52
Chapter 11: Arrays and Vectors
Arrays of objects
• draw method:
public void draw(Graphics2D g2)
{ for (int i = 0; i < cornersSize; i++)
{ Point2D.Double from = corners[i];
Point2D.Double to
= corners[(i + 1) % cornersSize];
g2.draw(new Line2D.Double(from, to));
}
• Why not just
static void drawPolygon(Graphics2D g2,
Point2D.Double[] a)
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
53
Chapter 11: Arrays and Vectors
Figure 14
The Output of the
PolygonTest program
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
54
Chapter 11: Arrays and Vectors
Program PolygonTest.java
import
import
import
import
import
java.applet.Applet;
java.awt.Graphics;
java.awt.Graphics2D;
java.awt.geom.Line2D;
java.awt.geom.Point2D;
public class PolygonTest extends Applet
{ public void paint(Graphics g)
{ Graphics2D g2 = (Graphics2D)g;
Polygon triangle
triangle.add(new
triangle.add(new
triangle.add(new
= new Polygon(3);
Point2D.Double(40, 40));
Point2D.Double(120, 160));
Point2D.Double(20, 120));
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
55
Chapter 11: Arrays and Vectors
double x = 200;
double y = 200;
double r = 50;
Polygon pentagon = new Polygon(5);
for (int i = 0; i < 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.
*/
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
56
Chapter 11: Arrays and Vectors
class Polygon
{ /**
Constructs a polygon with a given number of corner
points.
@param n the number of corner points.
*/
public Polygon(int n)
{ corners = new Point2D.Double[n];
cornersSize = 0;
}
/**
Adds a corner point of the polygon. The point is
ignored if the maximum number of points has been added.
@param p the corner point
*/
public void add(Point2D.Double p)
{ if (cornersSize < corners.length)
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
57
Chapter 11: Arrays and Vectors
{
corners[cornersSize] = p;
cornersSize++;
}
}
/**
Draws the polygon.
@param g2 the graphics context
*/
public void draw(Graphics2D g2)
{ for (int i = 0; i < cornersSize; i++)
{ Point2D.Double from = corners[i];
Point2D.Double to
= corners[(i + 1) % corners.length];
g2.draw(new Line2D.Double(from, to));
}
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
58
Chapter 11: Arrays and Vectors
private Point2D.Double[] corners;
private int cornersSize;
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
59
Chapter 11: Arrays and Vectors
Program CloudTest.java
import
import
import
import
import
import
java.applet.Applet;
java.awt.Graphics;
java.awt.Graphics2D;
java.awt.geom.Ellipse2D;
java.awt.geom.Point2D;
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 < CLOUD_SIZE; i++)
{ // generate two random numbers between 100 and 200
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
60
Chapter 11: Arrays and Vectors
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.
@param n the number of dots.
*/
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
61
Chapter 11: Arrays and Vectors
public Cloud(int n)
{ dots = new Point2D.Double[n];
dotsSize = 0;
}
/**
Sets a dot point of the cloud. The point is
ignored if the maximum number of points has been added.
@param p the dot point
*/
public void add(Point2D.Double p)
{ if (dotsSize < dots.length)
{ dots[dotsSize] = p;
dotsSize++;
}
}
/**
Draws the cloud.
@param g2 the graphics context
*/
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
62
Chapter 11: Arrays and Vectors
public void draw(Graphics2D g2)
{ final double SMALL_CIRCLE_RADIUS = 2;
for (int i = 0; i < dotsSize; i++)
{ Ellipse2D.Double smallCircle
= new Ellipse2D.Double(
dots[i].getX() - SMALL_CIRCLE_RADIUS,
dots[i].getY() - SMALL_CIRCLE_RADIUS,
2 * SMALL_CIRCLE_RADIUS,
2 * SMALL_CIRCLE_RADIUS);
g2.draw(smallCircle);
}
}
private Point2D.Double[] dots;
private int dotsSize;
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
63
Chapter 11: Arrays and Vectors
Figure 15
The Output of the
CloudTest Program
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
64
Chapter 11: Arrays and Vectors
Vectors
• Dynamically growing array of objects
Vector products
= new Vector();
• No need to set length. Can add as many
elements as desired
Product p = . . .;
products.add(p);
• Overwrite existing element
©2000, John Wiley &p);
Sons, Inc.
products.set(i,
Horstmann/Java Essentials, 2/e
65
Chapter 11: Arrays and Vectors
Vectors
• Get current size:
for (i=0; i<products.size(); i++)
• Must use cast to get elements
Product p = (Product)products.get(i);
• Must wrap numbers into wrapper classes
data.add(new Double(3.14));
x = ((Double)data.get(i)).doubleValue();
• Can copy into array (after growing stops)
Product[] a = new Product[v.size()];
v.copyInto(a);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
66
Chapter 11: Arrays and Vectors
Program Table2.java
public class Table2
{ public static void main(String[] args)
{ final int COLUMN_WIDTH = 10;
int[][] powers = new int[10][8];
for (int i = 0; i < powers.length; i++)
for (int j = 0; j < powers[i].length; j++)
powers[i][j] = (int)Math.pow(i + 1, j + 1);
printTable(powers, COLUMN_WIDTH);
}
/**
Prints a two-dimensional array of integers
@param table the values to be printed
@param width the column width
*/
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
67
Chapter 11: Arrays and Vectors
2D Arrays
• Store table of powers xy
1
2
3
. .
1
4
9
.
1
8
27
1
1
16 32
81 243
• int[][] powers
= new int[rows][columns]
• powers[3][4] = Math.pow(3, 4);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
68
Chapter 11: Arrays and Vectors
public static void printTable(int[][] table, int width)
{ for (int i = 0; i < table.length; i++)
{ for (int j = 0; j < table[i].length; j++)
{ System.out.print(format(table[i][j], width));
}
System.out.println();
}
}
/**
Formats an integer to fit in a field of constant width.
@param n the integer to format
@param width the field width
@return a string of length width, consisting of
leading spaces followed by the number n
*/
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
69
Chapter 11: Arrays and Vectors
public static String format(int n, int width)
{ String nstr = "” + n;
// pad with spaces
while (nstr.length() < width)
nstr = ” ” + nstr;
return nstr;
}
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
70
Chapter 11: Arrays and Vectors
Figure 16
A Two-Dimensional Array
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
71
Chapter 11: Arrays and Vectors
Figure 17
Glider
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
72
Chapter 11: Arrays and Vectors
Figure 18
Glider Gun
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
Related documents