CSC 245 Chapter 3, Spring 2015
Lebanese American University · Objects and Data Abstraction · 22 pages
Showing the first 10 of 22 pages. Download the PDF to see all of it.
More CSC 245 files
Show the text of this chapter
Chapter 3
Collection Classes
I Java Arrays
I ADT for Bag of Integers
• Specification
• IntArrayBag ADT
• Bag ADT
• Invariants
I Interactive Testing Applet
I Sequence ADT
Computer Programming II (v1.20)
WK–2
Java Arrays
I Contiguous locations of memory
• Same name & type.
I Elements accessed via subscripts
• scores[2]
• Index range is 0 to length − 1
• ArrayIndexOutOfBoundsException
I Length of an array
• Public data member, length.
scores.length
scores[0]
scores[1]
scores[2]
scores[3]
Computer Programming II (v1.20)
WK–3
Java Arrays…
I Declaration
• int scores[] = new int[4];
• int scores[];
scores = new int[4];
• int scores[] = {7, 22, 19, 56};
I Assignment
• scores[0] = 7;
• scores[1] = 22;
• scores[2] = 19;
• scores[3] = 56;
I Array as Object
• int[] exams = scores;
scores[0]
scores[1]
scores[2]
scores[3]
scores
exams
Computer Programming II (v1.20)
WK–4
Java Arrays…
I Clones
• int exams[] =
(int[]) scores.clone();
• exams[2] = 42;
I Array Initialization
• Numeric primitive types: zero.
• Boolean primitive types: false.
• Object references: null.
[0]
[1]
[2]
[3]
56
19
22
7
scores
[0]
[1]
[2]
[3]
56
42
22
7
exams
Computer Programming II (v1.20)
WK–5
Parameter Passing
I Call-by-value
• Caller passes a copy of a parameter to the called method.
• Changes are not reflected in the original parameter.
I Call-by-reference
• Caller passes a reference to the parameter to the called method.
• Changes made by the called method are seen by the caller.
I Java Policy
• Primitive types are passed by value—scalar quantities.
• Object references, arrays, etc., are passed by reference.
Computer Programming II (v1.20)
WK–6
Java Arrays…
Array Parameter Example
I put42s Method
public static void put42s
(int[] data)
• Put 42 in all elements of the array.
I Parameters
data—an array of integers.
I Postcondition
• All elements of array data have
been set to 42.
I Implementation
public static void puts42
(int[ ] data) {
int i;
for (i = 0;
i < data.length;
i++) {
data[i] = 42;
}
}
I Using Parameters
int[] example = new int[7];
put42s(example);
Computer Programming II (v1.20)
WK–7
Bag of Integers
I Collections
• Objects that can hold a group of items.
• Implemented as a class.
• Class defines methods to add, remove, & examine items.
I Bag of Integers
• Holds a collection of integers.
• First implementation uses integer array.
• Other implementations use linked lists…
Computer Programming II (v1.20)
WK–8
Bag of Integers…
I Creation
• Bag starts empty
I Initial state.
I Modifying Operations
• Add number to a bag.
I Allow multiple copies.
• Remove number from a bag.
I If number is present in bag!
I Only one copy removed if more than one copy in bag.
I Queries
• How many occurrences of a given number?
• How many numbers in bag?
Computer Programming II (v1.20)
WK–9
Bag ADT—Specification
I Implementation
• To be decided!
I Class Definition
• Class header.
• Constructor(s).
• Public methods.
I Public Interface
• Specification defines public interface.
• Can use Bag ADT without knowing implementation details.
Computer Programming II (v1.20)
WK–10
Bag ADT—Specification…
I Class Name
• Implemented as class IntArrayBag.
I Constructors
• public IntArrayBag(int initialCapacity)
I Create a bag with an initial capacity.
I Capacity is automatically increased when capacity is reached.
• public IntArrayBag()
I Initial capacity of 10.
Computer Programming II (v1.20)
WK–11
Bag ADT—Specification…
I Modification Methods
• public void add(int element)
I Add the integer, element, to the bag.
I A new copy is added if already present.
• public boolean remove(int target)
I Remove the number target from the bag if present.
I Return true if number present, false otherwise.
• public void addAll(IntArrayBag addend)
I Add contents of a bag to existing contents of this bag.
Computer Programming II (v1.20)
WK–12
Bag ADT—Specification…
I Query Methods…
• public int getCapacity()
I Returns capacity of current bag.
I Modification Methods…
• public void ensureCapacity(int minimumCapacity)
I Increases capacity of bag to a minimum.
• public void trimToSize()
I Reduces capacity of bag to number of items currently in bag.
I Minimizes memory usage.
Computer Programming II (v1.20)
WK–13
Bag ADT—Specification…
I Bag Producing Methods
• public static IntArrayBag union
(IntArrayBag b1, IntArrayBag b2)
I Returns new bag containing numbers in both bags.
• public Object clone()
I Returns a new bag.
I Contents same as contents of this bag.
Computer Programming II (v1.20)
WK–14
Bag ADT—Specification…
I Query Methods
• public int size()
I Returns number of integers in bag.
• public int countOccurrences(int target)
I Determines number of times integer target appears in bag.
• public int getCapacity()
I Returns current capacity of bag.
Computer Programming II (v1.20)
WK–15
Bag ADT—Code Examples
I Bag Creation & Adding Elements
// New bag is empty.
IntArrayBag firstBag = new IntArrayBag();
firstBag.add(8);
// firstBag has 1 element: 8.
firstBag.add(4);
// firstBag has 2 elements: 8 & 4.
firstBag.add(8);
// firstBag has 3 elements: Two 8s & one 4.
I At end, Bag firstBag contains 3 elements.
• Two 8s and one 4.
Computer Programming II (v1.20)
WK–16
Bag ADT—Code Examples…
I Query Methods
System.out.println(firstBag.countOccurrences(1));
System.out.println(firstBag.countOccurrences(4));
System.out.println(firstBag.countOccurrences(8));
• Output
I 0
I 1
I 2
Computer Programming II (v1.20)
WK–17
Bag ADT—Code Examples…
I Bag Creation & Adding Elements…
IntArrayBag helter = new IntArrayBag();
IntArrayBag skelter = new IntArrayBag();
helter.add(8);
skelter.add(4);
skelter.add(8);
// skelter has two elements: 4 & 8.
// helter has one element: 8.
helter.addAll(skelter);
// helter has three elements: two 8s & one 4.
Computer Programming II (v1.20)
WK–18
Bag ADT—Code Examples…
I Bag Creation…
IntArrayBag part1 = new IntArrayBag();
IntArrayBag part2 = new IntArrayBag();
part1.add(8);
part1.add(9);
// Two elements in part1: 8 & 9.
part2.add(4);
part2.add(8);
// Two elements in part2: 4 & 8.
IntArrayBag total = IntArrayBag.union(part1, part2);
// 4 elements in total: 4, 9, & two 8s.
I Equivalent statements
IntArrayBag total = new IntArrayBag();
total.addAll(part1); total.addAll(part2);
Computer Programming II (v1.20)
WK–19
Bag ADT—Code Examples…
I Bag Creation…
IntArrayBag b = new IntArrayBag();
b.add(42);
IntArrayBag c = (IntArrayBag) b.clone();
• Bag b is different from bag c.
• Bags b & c each contain one integer: 42.
Computer Programming II (v1.20)
WK–20
Bag ADT—Specification…
I Out of Memory Limitation
• Store integers in an array.
• Allocate larger array when more capacity is needed.
• Array allocated on heap.
• Exception OutOfMemoryError indicates insufficient memory.
I Other Limitations
• Array indexed by integers.
• Java integers limited to Integer.MAX_VALUE.
• Machines normally run out of memory before exceeding integer limit.
Computer Programming II (v1.20)
WK–21
Class IntArrayBag—Specification…
I Class IntArrayBag
• An IntArrayBag is a collection of int numbers. The same number may
appear multiple times in a bag.
• Limitations
1. Bag capacity can change after creation, but maximum capacity is
limited by machine memory. The constructor, addItem, clone, and
union throw an OutOfMemoryError when memory is exhausted.
2. A bag's capacity cannot exceed the maximum integer 2,147,483,647
(Integer.MAX_VALUE). Any attempt to create a larger capacity
results in a failure due to an arithmetic overflow.
3. Because of the slow linear algorithms of this class, large bags will
have poor performance.
Computer Programming II (v1.20)
WK–22
Class IntArrayBag—Specification…
I First Constructor
public IntArrayBag()
• Initialize an empty bag with an initial capacity of 10.
Note that the add method works efficiently (without needing more
memory) until this capacity is reached.
• Parameters
none .
• Postcondition
This bag is empty and has an initial capacity of 10.
• Throws: OutOfMemoryError
Indicates insufficient memory for: new int[10].
Computer Programming II (v1.20)
WK–23
Class IntArrayBag—Specification…
I Second Constructor
public IntArrayBag(int initialCapacity)
• Initialize empty bag with a specified initial capacity. The add method
works efficiently (without needing more memory) until this capacity is
reached.
• Parameters
initialCapacity—initial capacity of this bag.
• Precondition
initialCapacity is non-negative.
• Postcondition
This bag is empty and has a capacity of initialCapacity.
• Throws:
IllegalArgumentException—initialCapacity is negative.
OutOfMemoryError—insufficient memory for:
new int[initialCapacity].
Computer Programming II (v1.20)
WK–24
Class IntArrayBag—Specification…
I add Method
public void add(int element)
• Add a new element to this bag. Increase capacity of bag before adding
element if need be.
• Parameters
element—new element that is being added.
• Postcondition
A new copy of the element has been added to this bag.
• Throws:
OutOfMemoryError—insufficient memory for increasing the capacity.
• Note
Capacity over Integer.MAX_VALUE generates arithmetic overflow.
Computer Programming II (v1.20)
WK–25
Class IntArrayBag—Specification…
I addAll Method
public void addAll(IntArrayBag addend)
• Add the contents of another bag to this bag.
• Parameters
addend—a bag whose contents are being added to this bag.
• Precondition
The parameter, addend, is not null.
• Postcondition
The elements from addend have been added to this bag.
• Throws:
NullPointerException—parameter addend is null.
OutOfMemoryError—insufficient memory for increasing the capacity.
• Note
Capacity over Integer.MAX_VALUE generates arithmetic overflow.
Computer Programming II (v1.20)
WK–26
Class IntArrayBag—Specification…
I clone Method
public Object clone()
• Generate a copy of this bag.
• Returns
A copy of this bag. Changes to copy will not affect this bag or vice versa.
Return value must be typecast to an IntArrayBag before used.
• Throws
OutOfMemoryError—insufficient memory for creating clone.
Computer Programming II (v1.20)
WK–27
Class IntArrayBag—Specification…
I countOccurrences Method
public int countOccurrences(int target)
• Accessor method to count occurrences of a particular element in this bag.
• Parameters
target—the element that needs to be counted.
• Returns
The number of times that target occurs in this bag.
Computer Programming II (v1.20)
WK–28
Class IntArrayBag—Specification…
I ensureCapacity Method
public void ensureCapacity(int minumumCapacity)
• Change the current capacity of this bag.
• Parameters
minumumCapacity—the new capacity for this bag.
• Postcondition
This bag's capacity has been changed to at least minumumCapacity.
Capacity is unchanged if already greater than parameter.
• Throws
OutOfMemoryError—indicates insufficient memory for:
new int[minimumCapacity].
Computer Programming II (v1.20)
WK–29
Class IntArrayBag—Specification…
I getCapacity Method
public int getCapacity()
• Accessor method that determines the current capacity of this bag. The
add method works efficiently (w/o needing more memory) until this
capacity is reached.
• Returns
the current capacity of this bag.
Computer Programming II (v1.20)
WK–30
Class IntArrayBag—Specification…
I remove Method
public boolean remove(int target)
• Remove one copy of a specified element from this bag.
• Parameters
target—the element to remove from this bag.
• Postcondition
If target was found in this bag, then one copy has been removed and the
method returns true. Otherwise, this bag remains unchanged and the
method returns false.
Computer Programming II (v1.20)
WK–31
Class IntArrayBag—Specification…
I size Method
public int size()
• Accessor method to determine the number of elements in this bag.
• Returns
the number of elements in this bag.
Computer Programming II (v1.20)
WK–32
Class IntArrayBag—Specification…
I trimToSize Method
public void trimToSize()
• Reduce the current capacity of this bag to the number of elements in it.
• Postcondition
This bag's capacity has been changed to its actual size.
• Throws
OutOfMemoryError—indicates insufficient memory for altering
capacity.
Computer Programming II (v1.20)
WK–33
Class IntArrayBag—Specification…
I union Method
public static IntArrayBag union
(IntArrayBag b1, IntArrayBag b2)
• Create a new bag that contains all the elements from two other bags.
• Parameters
b1—the first of two bags.
b2—the second of two bags.
• Precondition
Neither b1 nor b2 is null.
• Returns
a new bag that is the union of b1 and b2.
• Throws
NullPointerException—indicates that of the arguments is null.
OutOfMemoryError—indicates insufficient memory for the new bag.
• Note
Capacity over Integer.MAX_VALUE generates arithmetic overflow.
Computer Programming II (v1.20)
WK–34
Class IntArrayBag—Demo
I Program Task
• User types ages with a negative sentinel; program enters ages into a bag.
• User types an age which the program removes from the bag.
I Session
% java BagDemonstration
Type the ages of your family members.
Type a negative number at the end and press return.
5 19 47 -1
Type those ages again. Press return after each age.
Age: 19
Yes, I've got that age and will remove it.
Age: 36
No, that age does not occur!
Age: 5
Yes, I've got that age and will remove it.
Age: 47
Yes, I've got that age and will remove it.
May your family live long and prosper.
%
Computer Programming II (v1.20)
WK–35
Class BagDemonstration
// This small demonstration program shows how to use the
// IntArrayBag class from the edu.colorado.collections package.
import edu.colorado.collections.IntArrayBag;
import edu.colorado.io.EasyReader;
class BagDemonstration
{
private static EasyReader stdin = new EasyReader(System.in);
public static void main(String[ ] args)
{
IntArrayBag ages = new IntArrayBag( );
getAges(ages);
checkAges(ages);
System.out.println("May your family live long and prosper.");
}
...
}
Computer Programming II (v1.20)
WK–36
Class BagDemonstration…
// The getAges method prompts the user to type in the ages of family members. These ages
// are read and placed in the ages bag, stopping when the user types a negative number.
// This program does not worry about the possibility of running out of memory.
public static void getAges(IntArrayBag ages)
{
int userInput; // An age from the user's family
System.out.println("Type the ages of your family members.");
System.out.println
("Type a negative number at the end and press return.");
userInput = stdin.intInput( );
while (userInput >= 0)
{
ages.add(userInput);
userInput = stdin.intInput( );
}
}
Computer Programming II (v1.20)
WK–37
Class BagDemonstration…
//The checkAges method prompts the user to type in the ages of family members once
// again. Each age is removed from the ages bag when it is typed, stopping when the bag is
// empty (or the user types a negative number).
public static void checkAges(IntArrayBag ages)
{
int userInput; // An age from the user's family
System.out.print("Type those ages again. ");
System.out.println("Press return after each age.");
while (ages.size( ) > 0) {
userInput = stdin.intQuery("Age: ");
if (ages.countOccurrences(userInput) == 0)
System.out.println("No, that age does not occur!");
else {
System.out.println("Yes, I've got that age and will remove it.");
ages.remove(userInput);
}
}
}
Computer Programming II (v1.20)
WK–38
Class BagDemonstration…
I See BagDemonstration.java listing
Computer Programming II (v1.20)
WK–39
Class IntArrayBag—Design
I Basic Structure
• Store numbers in front part of array.
• Order is irrelevant.
I Example
• Bag with three entries: two 4s & one 8.
Array of integers
Irrelevant Contents
8
[0]
4
[1]
8
[2]
[3]
[4]
[5]
...
Computer Programming II (v1.20)
WK–40
Class IntArrayBag—Design…
I Example…
• Valid storage schemes.
Array of integers
Irrelevant Contents
8
[0]
8
[1]
4
[2]
[3]
[4]
[5]
...
4
[0]
8
[1]
8
[2]
[3]
[4]
[5]
...
Computer Programming II (v1.20)
WK–41
Class IntArrayBag—Design…
I Basic Structure…
• Store numbers in array.
• Keep track of number of items in array.
Array of integers
Irrelevant Contents
8
[0]
8
[1]
4
[2]
[3]
[4]
[5]
...
3
Number of items
stored in array
Computer Programming II (v1.20)
WK–42
Class IntArrayBag—Design…
I Basic Class Definition
public class IntArrayBag implements Cloneable
{
private int[] data;
// An array to store elements
private int manyItems; // How much of the array is used?
// public methods go here.
}
Computer Programming II (v1.20)
WK–43
Invariant of an ADT
I Definition
• Rules governing the use of instance variables by methods.
• Invariant is valid when a method is invoked.
I Constructors are the exception.
• Invariant is valid when a method call completes.
• Document in class declaration.
I Example—Class IntArrayBag
• Number of elements is stored in instance variable manyItems.
• Numbers stored in data[0] through data[manyItems – 1].
• For empty bag, do not care about items stored in array data.
Computer Programming II (v1.20)
WK–44
Class IntArrayBag—Design…
I Constructor
• Initializes instance variables to represent an empty bag.
• Array size is initial capacity of bag.
data [0]
[1]
[2]
[3]
[4]
[5]
...
Irrelevant Contents
0
manyItems
Computer Programming II (v1.20)
WK–45
Class IntArrayBag—Design…
I Constructor—Implementation
public IntArrayBag(int initialCapacity)
{
if (initialCapacity < 0)
throw new IllegalArgumentException
("initialCapacity is –ve: " + initialCapacity");
manyItems = 0;
data = new int[initialCapacity];
}
Computer Programming II (v1.20)
WK–46
Class IntArrayBag—Design…
I add Method
• Check capacity & double existing capacity if needed.
• Store number in next free slot.
• Increment element count.
public void add(int element)
b.add(42);
I Before
I After
4
8
2
b.manyItems
b.data
4
8
7
3
b.manyItems
b.data
Computer Programming II (v1.20)
WK–47
Class IntArrayBag—Design…
I add Method—Implementation
public void add(int element)
{
if (manyItems == data.length)
{
// Double the capacity and add 1: this works even if manyItems is 0.
// However, in the case that manyItems*2+1 is beyond
// Integer.MAX_VALUE, there will be an arithmetic overflow and
// the bag will fail.
ensureCapacity(manyItems * 2 + 1);
}
data[manyItems++] = element;
}
Computer Programming II (v1.20)
WK–48
Class IntArrayBag—Design…
I remove Method
• Find index of target value in array.
• Store item in last slot of array in target slot.
• Decrement element count.
public boolean remove(int element)
b.remove(8);
I Before
I After
4
8
7
4
b.manyItems
b.data
4
4
7
3
b.manyItems
b.data
4
Computer Programming II (v1.20)
WK–49
Class IntArrayBag—Design…
I remove Method
public boolean remove(int target) {
int
index;
// Location of target in data array.
// First, set index to location of target in data array; range is 0 to manyItems – 1;
// If target is not in array, index will be set to manyItems.
for (index = 0;
(index < manyItems) && (target != data[index]);
index++)
; // Do nothing
if (index == manyItems)
return false; // Target not found; nothing is removed.
else {
manyItems--;
data[index] = data[manyItems];
return true;
}
}
Computer Programming II (v1.20)
WK–50
Class IntArrayBag—Design…
I countOccurrences Method
public int countOccurrences(int target)
{
int answer;
int index;
answer = 0;
for (index = 0; index < manyItems; index++)
{
if (target == data[index])
answer++;
}
return answer;
}
Computer Programming II (v1.20)
WK–51
Class IntArrayBag—Design…
I addAll Method
• Ensure capacity is big enough.
• Copy items from addend.data to bag’s own data array.
• Update number of items in bag.
public void addAll(IntArrayBag addend)
{
// If addend is null, a NullPointerException is thrown.
// If total number of items > Integer.MAX_VALUE, overflow failure.
ensureCapacity(manyItems + addend.manyItems);
System.arrayCopy(addend.data, 0, data, manyItems,
addend.manyItems);
manyItems += addend.manyItems;
}
Computer Programming II (v1.20)
WK–52
Class IntArrayBag—Design…
I union Method
IntArrayBag b3 = IntArrayBag.union(b1, b2);
public static IntArrayBag(IntArrayBag b1,
IntArrayBag b2) {
// Throw NullPointerException if b1 or b2 are null.
// Failure by arithmetic overflow if total number of items is too big.
IntArrayBag answer = new
IntArrayBag(b1.getCapacity() + b2.getCapacity());
System.arrayCopy(b1.data, 0, answer.data, 0,
b1.manyItems);
System.arrayCopy(b2.data, 0, answer.data,
b1.manyItems, b2.manyItems);
answer.manyItems = b1.manyItems + b2.manyItems;
return answer;
}
Computer Programming II (v1.20)
WK–53
Class IntArrayBag—Design…
I ensureCapacity Method
public void ensureCapacity(int minimumCapacity)
{
int[] biggerArray;
if (data.length < minimumCapacity)
{
biggerArray = new int[minimumCapacity];
System.arrayCopy(data, 0, biggerArray, 0,
manyItems);
data = biggerArray;
}
}
Computer Programming II (v1.20)
WK–54
Class IntArrayBag—Design…
I getCapacity Method
public int getCapacity()
{
return data.length;
}
I size Method
public int size()
{
return manyItems;
}
Computer Programming II (v1.20)
WK–55
Class IntArrayBag—Design…
I trimToSize Method
public void trimToSize()
{
int trimmedArray;
if (data.length != manyItems)
{
trimmedArray = new int[manyItems];
System.arrayCopy(data, 0, trimmedArray, 0,
manyItems);
}
}
Computer Programming II (v1.20)
WK–56
Class IntArrayBag—Design…
I clone Method
• Create copy of bag.
• Create copy of objects referred by bag's instance variables.
I super.clone();
I System.arrayCopy(…);
null
0
answer.manyItems
answer.data
this.manyItems
3
this.data
4
8
7
3
answer.manyItems
answer.data
4
8
7
Computer Programming II (v1.20)
WK–57
Class IntArrayBag—Design…
I clone Method—Implementation
public Object clone() {
// Clone an IntArrayBag object.
IntArrayBag answer;
try {
answer = (IntArrayBag) super.clone();
}
catch (CloneNotSupportedException e) {
// Exception implies a programming error, most likely forgot "implements
// Cloneable" in class header.
throw new RuntimeException
("Class does not implement Cloneable");
}
answer.data = (int[]) data.clone();
return answer;
}
Computer Programming II (v1.20)
WK–58
Bag ADT—Time Analysis
I Counting Operations
• Expressed as a function of bag capacity (c) or size (n).
I Loop
for (index = 0; index < manyItems; index++)
if (target == data[index])
answer++;
• n × (number of statements in loop) ⇒ O(n)
I Constructor
• Allocates array of initialCapacity integers.
• Integers initialized to zero.
⇒ O(c)
Computer Programming II (v1.20)
WK–59
Bag ADT—Time Analysis…
c is the bag's capacity
n1 & n2 are the sizes of the bags
Linear in the size of the added bag
Linear time
Constant time
c is the initial capacity
O(c)
clone
O(n1+n2)
b1.addAll(b2)
with capacity increase
O(n2)
b1.addAll(b2)
without capacity increase
O(n)
add
with capacity increase
O(1)
add
without capacity increase
O(c)
Constructor
Time Analysis
Operation
Computer Programming II (v1.20)
WK–60
Bag ADT—Time Analysis…
c1 & c2 are the bags’ capacities
O(c1+c2)
union of
b1 and b2
Linear time
Constant time
Linear time
Constant time
c is the specified minimum
capacity
Linear time
O(n)
trimToSize
O(1)
size
O(n)
remove
O(1)
getCapacity
O(c)
ensureCapacity
O(n)
countOccurrences
Time Analysis
Operation
Computer Programming II (v1.20)
WK–61
Applets for Testing
Computer Programming II (v1.20)
WK–62
Applets for Testing
I Use public interface to
exercise class methods.
• Add elements.
• Obtain size.
• Count occurrences.
Computer Programming II (v1.20)
WK–63
Applets for Testing…
I Template
• Import statements
• Class definition
I IntArrayBag object
I GUI components of applet.
I init method.
I Implementations of action listeners
• Events: buttons or input fields.
I Implementations of other methods.
Computer Programming II (v1.20)
WK–64
Applets for Testing…
I Import Statements
• Class being tested.
I Not needed if class is in same directory.
import edu.colorado.collections.IntArrayBag;
• Java classes needed by applet.
import java.applet.Applet; // Provides Applet class
import java.awt.*; // Provides Button class…
import java.awt.event.*; // ActionEvent, ActionListener.
Computer Programming II (v1.20)
WK–65
Applets for Testing…
I Class Definition
public class BagApplet extends Applet {
// IntArrayBag object for applet to manipulate
IntArrayBag b = new IntArrayBag();
// Declare applet’s components: buttons, text fields, & other GUI comps
...
public void init() {
...
}
// Implementation of action listeners.
...
// Implementation of other methods.
...
}
Computer Programming II (v1.20)
WK–66
Applets for Testing…
I Applet’s GUI Components
• Buttons, labels, text fields, and a text area.
// These are the interactive Components that will appear in the Applet.
// We declare one Button for each IntArrayBag method that we want
// to be able to test. If the method has an argument, then there is also a
// TextField where the user can enter the value of the argument. At the
// bottom, there is a TextArea to write messages.
Button sizeButton = new Button("size( )");
Button addButton = new Button("add( )");
TextField elementText = new TextField(10);
Button countOccurrencesButton =
new Button("countOccurrences( )");
TextField targetText
= new TextField(10);
TextArea feedback = new TextArea(7, 60);
Computer Programming II (v1.20)
WK–67
Applets for Testing…
I init Method
• Called by applet viewer after creating applet object.
I Equivalent to an application’s main method.
• Adds GUI components.
I Sets up layout of applet.
• Activates GUI components.
I Creates & attaches listeners to selected GUI components.
Computer Programming II (v1.20)
WK–68
Applets for Testing…
I Adding GUI Components
• Use add method.
public void add(Component)
• Adds a GUI component to applet object.
I Buttons, labels,…
• add(sizeButton);
• add(new Label("Test program created a bag"));
• Typical components:
I Button—activates action when pressed.
I Label—displays message on screen.
I TextField—accepts or displays user input (one line).
I TextArea—accepts or displays multiple lines of text.
Computer Programming II (v1.20)
WK–69
Applets for Testing…
I Activating GUI Components
• Create listeners.
• Attach listeners to components.
I Listeners
• Describe actions to be taken in reaction to events.
I Button presses, CR in a text field, etc.
• SizeListener—sizeButton is clicked.
• AddListener—addButton is clicked or CR entered in
elementText field.
• CountOccurrencesListener—countOccurrencesButton is
clicked or CR entered in targetText field.
Computer Programming II (v1.20)
WK–70
Applets for Testing…
I Implementing Action Listeners
• Define inner class.
I Visible only within another class definition.
I Has access to all instance variables.
• Attach instance of inner class as listener.
I Pattern
class
implements ActionListener
{
void actionPerformed(ActionEvent event)
{
...
}
}
Computer Programming II (v1.20)
WK–71
Applets for Testing…
I Action Listeners—“size()” Button
class SizeListener implements ActionListener
{
void actionPerformed(ActionEvent event)
{
feedback.append("The bag has size " +
b.size + "\n");
}
}
I Attaching Listeners
• sizeButton(addActionListener(new SizeListener()));
Computer Programming II (v1.20)
WK–72
Applets for Testing…
I Action Listeners—“add()” Button & Text Field
• Must handle empty or mistyped number.
I NumberFormatException when interpreted as integer.
• Use try-catch block.
I Attaching Listener
• AddListener addListener = new AddListener();
• addButton.addActionListener(addListener);
• elementText.addActionListener(addListener);
Computer Programming II (v1.20)
WK–73
Applets for Testing…
I Action Listeners—“add()” Button & Text Field
class AddListener implements ActionListener {
void actionPerformed(ActionEvent event) {
try {
String userInput = elementText.getText();
int element = Integer.parseInteger(userInput);
b.add(element);
feedback.append
(element +" has been added to the bag");
}
catch (NumberFormatException e) {
feedback.append
("Type an integer before clicking button");
elementText.requestFocus();
elementText.selectAll();
}
}}
Computer Programming II (v1.20)
WK–74
Applets for Testing
I See BagApplet.java listing
Computer Programming II (v1.20)
WK–75
Applets for Testing…
I HTML File
• <APPLET CODE="BagApplet.class"
WIDTH=480 HEIGHT=340>
</APPLET>
I Starting Applet
• Browser
• appletviewer
Computer Programming II (v1.20)
WK–76
Sequence ADT
I Similar to a bag.
• Collection of items.
I Defines current item.
I Has methods that step through elements.
• Useable in a loop.
I Contains doubles.
Computer Programming II (v1.20)
WK–77
Class DoubleArraySeq—Specification
I Constructors
• public void DoubleArraySeq()
I Empty sequence with initial capacity of 10.
• public void DoubleArraySeq(int capacity)
I Empty sequence with specified initial capacity.
I size Method
• public int size()
I Returns number of elements in the sequence.
Computer Programming II (v1.20)
WK–78
Class DoubleArraySeq—Specification…
I Examining a Sequence
• public void start()
I Initialize current element to point to sequence’s first element.
• public double getCurrent()
I Return current element of sequence.
• public void advance()
I Update current to point to sequence’s next element.
• public boolean isCurrent()
I Does current point to an actual element of sequence?
I Is current pointing past sequence’s edge?
Computer Programming II (v1.20)
WK–79
Class DoubleArraySeq—Specification…
I Examining a Sequence—Example
for (numbers.start(); numbers.isCurrent();
numbers.advance())
{
System.out.println(numbers.getCurrent());
}
• Output
I 10.1
I 40.2
I 1.1
10.1
40.2
1.1
Computer Programming II (v1.20)
WK–80
Class DoubleArraySeq—Specification…
I addBefore & addAfter Methods
• public void addBefore(double element)
I Place new element before current.
I Make new element current.
I Sequence with no current adds at front.
I Empty sequence adds first element.
I May need to increase capacity.
I seq.addBefore(10.0);
• public void addAfter(double element)
I Similar to addBefore method.
I Place new element after current.
42.1
8.8
99.0
42.1
10.0
8.8
99.0
After
Before
Computer Programming II (v1.20)
WK–81
Class DoubleArraySeq—Specification…
I removeCurrent Method
• public boolean removeCurrent()
I Removes current element from sequence.
I Curren