Download cmp326: Programming Methods II LAB on Collection Framework

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
cmp326: Programming Methods II
LAB on Collection Framework
Task 1: Write TestPriorityQueue1.java. Trace the program by debugger.
import java.util.PriorityQueue;
public class TestPriorityQueue1
{
public static void main( String[] args )
{
// PriorityQueue of Double objects: queue of capacity 11
_______________ queue = new _________________();
// insert elements to queue
queue.offer( 3.2 );
queue.offer( 9.8 );
queue.offer( 5.4 );
System.out.print( "Polling from queue: " );
// display elements in queue
while ( queue.size() > 0 )
{
System.out.println( "first element to be removed " + queue.peek() ); // view top element
queue.remove(); // remove first element
} // end while
}// end of main
}//end of class
Task 2: Modify TestPriorityQueue1.java as shown below. After you complete the program trace the
program execution by debugger.
import java.util.Collections;
import java.util.Iterator;

Add the following statement to create PriorityQueue of Double with a comparator object that
reverses the natural ordering of the double values. //Use Collections.reverseOrder() method
__________________ queue2 = _______________();

Add the following three statements to populate PriorityQueue
queue2.offer(3.2);
queue2.offer(9.8);
1
queue2.offer(5.4);

Add the following statements to TestPriorityQueue1.java to get an iterator object to access
elements in the PriorityQueue object. Also we try to poll the elements of the PriorityQueue object
by using remove() method.
Iterator<Double> queue2Iterator = queue2.iterator();
while ( queue2Iterator.hasNext() ){
System.out.println( queue2Iterator.next() );
}
System.out.print( "Polling from queue: " );
// display elements in queue
while ( queue2.size() > 0 )
{
System.out.println( "first element to be removed " + queue2.peek() ); // view top element
queue2.remove(); // remove first element
} // end while
Task 3: Write Point.java that encapsulates two double instance variables as shown below.
public class Point implements ______________ {//implements Comparable interface
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX(){
return x;
}
public double getY(){
return y;
}
public void setX(double value){
x = value;
}
public void setY(double value){
2
y = value;
}
public int ______________(Point p2) {// add the name of this method
if (this.x < p2.x)
return -1;
else if (this.x == p2.x) {
// Secondary order on y-coordinates
if (this.y < p2.y)
return -1;
else if (this.y == p2.y)
return 0;
else
return 1;
} else
return 1;
}
public String toString() {
return "(" + x + ", " + y + ")";
}
}
Task 4: Write CompareY.java that implements java.util.Comparator interface as shown below. Fill-out
blank lines.
/**
* A comparator for comparing points on their y-coordinates. If y-coordinates
* are the same, compare their x-coordinator.
*/
public class CompareY implements __________________________{
public int compare(Point p1, Point p2) {
if (p1.getY() < p2.getY())
return -1;
else if (p1.getY() == p2.getY()) {
// Secondary order on x-coordinates
if (p1.getX() < p2.getX())
return -1;
else if (p1.getX() == p2.getX())
return 0;
else
return 1;
3
} else
return 1;
}
}
Task 5: Test your program by the TestPoint.java
import java.util.Arrays;
public class TestPoint {
// Each row in points represents a point
public static void main(String[] args) {
____________ = __________________ //create an array of 5 Point objects
for (int i = 0; i < points.length; i++) {
points[i] = new Point((int)(Math.random() * 100), (int)(Math.random() * 100));
}
System.out.println("Sort on x-coordinates");
Arrays.sort(points);
for (int i = 0; i < points.length; i++) {
System.out.println(points[i]);
}
System.out.println("Sort on y-coordinates");
Arrays.sort(points, new CompareY());
for (int i = 0; i < points.length; i++) {
System.out.println(points[i]);
}
}
}
Task 6: Write TestPriorityQueue2.java as shown below. Fill-out blank lines (or boxes).
import ________________ //import Collections class
import ___________________;// import Iterator interface
import java.util.PriorityQueue;
public class TestPriorityQueue2
{
public static void main( String[] args )
{
// Priority Queue of Points: queue of capacity 11
_______________queue = new __________________
4
// insert elements to queue
queue.offer( new Point(2, 3) );
queue.offer( new Point(2, 5) );
queue.offer( new Point(3, 1) );
System.out.print( "Polling from queue: " );
// display elements in queue
while ( queue.size() > 0 )
{
System.out.println( "Queue Element " + queue.peek() ); // view top element
queue.poll(); // remove top element
} // end while
//Create queue3 with PriorityQueue Constuctor with capacity and a comparator object
//Use Collections class method reverseOrder() to get a comparator object.
___________________ queue2 = new ___________________________
queue2.offer( new Point(2, 3) );
queue2.offer( new Point(2, 5) );
queue2.offer( new Point(3, 4) );
_______________ queue2Iterator = queue2.iterator();
while ( queue2Iterator.hasNext() ){
System.out.println( queue2Iterator.next() );
}
System.out.println( "Polling from queue: " );
// display elements in queue
while ( queue2.size() > 0 )
{
System.out.println( "first element to be removed " + queue2.peek() ); // view top element
queue2.poll(); // remove first element
} // end while
//Create queue3 with PriorityQueue Constuctor with capacity and a comparator object
//create new instance of CompareY as a comparator
_____________________ queue3 = new _______________________________
queue3.offer( new Point(2, 3) );
queue3.offer( new Point(2, 5) );
queue3.offer( new Point(3, 4) );
5
___________________ queue3Iterator = queue3.iterator();
while ( queue3Iterator.hasNext() ){
System.out.println( queue3Iterator.next() );
}
System.out.println( "Polling from queue: " );
// display elements in queue
while ( queue3.size() > 0 )
{
System.out.println( "first element to be removed " + queue3.peek() ); // view top element
queue3.__________ // remove first element Use remove method
} // end while
} // end main
} // end class PriorityQueueTest
Task7: Complete TestStack.java as shown below (Fill-out blank lines and or boxes)

Class Stack in the java.util package extends class Vector to implement a stack data structure.
o Stack method push() adds a Number object to the top of the stack.
o Stack method pop() removes the top element of the stack.
o If there are no elements in the Stack, method pop() throws a java.util.EmptyStackException.
o Method peek() returns the top element of the stack without popping the element off the stack.
o Method empty determines whether the stack is empty.
o Method search() returns the 1-based position where an object is on this stack. If the
object o occurs as an item in this stack, this method returns the distance from the top
of the stack of the occurrence nearest the top of the stack; the topmost item on the
stack is considered to be at distance 1.

Based on the following program template, create an empty Stack of Numbers. Class Number (in
java.lang package) is the super class of the type wrapper classes for the primitive numeric types (e.g.,
Integer, Double). By creating a Stack of Numbers, objects of any class that extends Number can be
pushed onto the Stack.
import java.util.________; //Use Stack
import java.util.__________________; //to handle empty stack exception
public class TestStack
{
public static void main( String[] args )
{
// create an object stack as an instance of Stack of Numbers
6
__________________stack = new ________________________;
________________ // push long value 12 to the stack
________________ // push int value 3456
________________ // push float value 1.2
_________________// push double value 123.45
_________________// invoke method printStack (statement A)
System.out.println("Search ...." + stack.search(3456)); // search an int value (statement B)
System.out.println("Search ...." + stack.search(123.45)); //search a double value (statement C)
// remove items from stack. Note: pop() method may throw EmptyStackException
// removing items from stack is done iteratively by using while loop. The while loop
// iterates infinitely until EmptyStackException is thrown
// When the EmptyStackException is thrown, the program exits (returns to the JRE)
} // end main
// display Stack contents
private ____________ printStack( ___________________ )
{
if (______________ )
System.out.println( "stack is empty\n" ); // the stack is empty
else // stack is not empty
System.out.println( "stack contains: "+ stack );
} // end method printStack
} // end class StackTest
Task 8: Rewrite the while loop to iterate elements as long as the stack is not empty (Use stack.empty() or
stack.isEmpty()).
Task 9: Write your own version of generic Stack named MyStack by using ArrayList. Fill-out the
blank lines of the MyStack.java
import java.util._______________;
7
import java.util._______________; //to handle empty stack exception
public class ___________
{
private ArrayList< T > stack; // ArrayList stack stores stack elements
/** default constructor creates a stack of the default size 10 * */
public MyStack()
{
__________________ // calls overloaded constructor (i.e., calls one argument constructor)
} // end no-argument Stack constructor
/**constructor creates a stack of the specified number of elements (capacity) */
public MyStack( int capacity )
{
int initCapacity = capacity > 0 ? capacity : 10; // validate
stack = _____________ // create ArrayList object with initCapacity
} // end one-argument Stack constructor
/** push element onto stack
* @param pushValue: value to be pushed onto the stack */
public void push( _______________ )
{
__________________ // use add method of the ArrayList to push pushValue onto the stack
} // end method push
/** return the top element if not empty; else throw EmptyStackException */
public ___ pop()
{
if ( _____________ ) // Use isEmpty method to see if stack is empty
______________________ //throws an EmptyStackException
/* remove and return top element of the stack. Use remove(index) method to remove the top of
the stack element. Top of the stack element is indexed by the current size of the stack -1. You
can get the current size of the stack by size() method. */
return _________( ___________ );
} // end method pop
} // end class
Task 10: Write TestMyStack.java to test MyStack. Fill-out the blank lines of the program template.
import ___________________; //to handle empty stack exception
8
public class TestMyStack
{
public static void main( String[] args )
{
Double[] doubleElements = { 1.1, 2.2, 3.3, 4.4, 5.5 };
Integer[] integerElements = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Create a Stack of Double elements with initial capacity 5
___________________ doubleStack = new ________________(5);
// Create a Stack of Integer elements with initial capacity 10
___________________ integerStack = new ________________(10);
// push elements of doubleElements onto doubleStack
testPush( "doubleStack", doubleStack, doubleElements );
testPop( "doubleStack", doubleStack ); // pop from doubleStack
// push elements of integerElements onto integerStack
testPush( "integerStack", integerStack, integerElements );
testPop( "integerStack", integerStack ); // pop from integerStack
} // end main
/**
* generic method testPush pushes elements onto the stack
* Each element pushed is displayed on the console */
public static ____ void testPush( String name , _________ stack,
___________ elements )
{
System.out.println( "Pushing elements onto " + name );
// push elements onto Stack
for ( __ element : elements ) //__ type of element of an array elements
{
System.out.print( " " + element );
____________; // push element onto stack
} // end for
} // end method testPush
/** generic method testPop pops elements from the stack
* Each element popped off is displayed on the console */
public static _____ void testPop( String name, _________ stack )
{
// remove items from stack. Note: pop() method may throw EmptyStackException
9
// removing items from stack is done iteratively by using while loop. The while loop
// iterates infinitely until EmptyStackException is thrown
// When the EmptyStackException object e is thrown, the program traces e by
//invoking e. printStackTrace().
//To display value popped off on the console, you need declare a variable popValue whose
//type is generic.
} // end method testPop
} // end class StackTest2
Task 10: Add empty() method to MyStack.java to test whether the stack is empty or not. Then rewrite
while loop of your TestMyStack.java by using empty() method.
10