CSCI 200 Lab 3 Using and implementing sets

Similar documents
CSCI Lab 9 Implementing and Using a Binary Search Tree (BST)

Problem 1: Building and testing your own linked indexed list

CSCI 200 Lab 1 Implementing and Testing Simple ADTs in Java

CSCI 200 Lab 2 Inheritance, Polymorphism & Data Streams

Problem 1: Building the BookCollection application

CSCI 200 Lab 4 Evaluating infix arithmetic expressions

List ADT. B/W Confirming Pages

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Collections and Iterators. Collections

Arrays. Chapter Arrays What is an Array?

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle

CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM

CMPSCI 187 / Spring 2015 Implementing Sets Using Linked Lists

public static boolean isoutside(int min, int max, int value)

CSE 143: Computer Programming II Summer 2015 HW6: 20 Questions (due Thursday, August 13, :30pm)

Project 3: Implementing a List Map

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

CSCI 200 Lab 11 A Heap-Based Priority Queue

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

CSIS 10B Lab 2 Bags and Stacks

Java Programming Style Guide

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

CPS122 Lecture: Detailed Design and Implementation

Homework 2: Imperative Due: 5:00 PM, Feb 15, 2019

List ADT. Announcements. The List interface. Implementing the List ADT

6.005 Elements of Software Construction Fall 2008

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

What is the Java Collections Framework?

Assignment3 CS206 Intro to Data Structures Fall Part 1 (50 pts) due: October 13, :59pm Part 2 (150 pts) due: October 20, :59pm

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

1 Shyam sir JAVA Notes

Announcements/Follow-ups

CSE 143: Computer Programming II Spring 2015 HW2: HTMLManager (due Thursday, April 16, :30pm)

CS110D: PROGRAMMING LANGUAGE I

public static void negate2(list<integer> t)

CS2110: Software Development Methods. Maps and Sets in Java

Due: 9 February 2017 at 1159pm (2359, Pacific Standard Time)

CS 170 Java Programming 1. Week 13: Classes, Testing, Debugging

The Java Collections Framework and Lists in Java Parts 1 & 2

Loops. In Example 1, we have a Person class, that counts the number of Person objects constructed.

The class Object. Lecture CS1122 Summer 2008

Homework 4: Hash Tables Due: 5:00 PM, Mar 9, 2018

COP 3330 Final Exam Review

Documentation Requirements Computer Science 2334 Spring 2016

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

Object-Oriented Programming in Java

Classes, interfaces, & documentation. Review of basic building blocks

Assignment 4: Hashtables

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Homework #10 due Monday, April 16, 10:00 PM

CS260 Intro to Java & Android 03.Java Language Basics

CS 151. Linked Lists, Recursively Implemented. Wednesday, October 3, 12

Lab 5 Random numbers!

Bags. Chapter 1. Copyright 2012 by Pearson Education, Inc. All rights reserved

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

CS 209 Sec. 52 Spring, 2006 Lab 6 - B: Inheritance Instructor: J.G. Neal

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

CS 151. Exceptions & Javadoc. slides available on course website. Sunday, September 9, 12

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

ACORN.COM CS 1110 SPRING 2012: ASSIGNMENT A1

Short Notes of CS201

Sets and Maps. Part of the Collections Framework

CSE 143: Computer Programming II Spring 2015 HW7: 20 Questions (due Thursday, May 28, :30pm)

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Software Design and Analysis for Engineers

Declarations and Access Control SCJP tips

CS 170 Java Programming 1. Week 12: Creating Your Own Types

Introduction to Programming Using Java (98-388)

CS Introduction to Data Structures Week 1 Thursday

Generic BST Interface

CS201 - Introduction to Programming Glossary By

Java Review: Objects

Building Java Programs

Documentation (and midterm review)

CS2110: Software Development Methods. Maps and Sets in Java

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Lab 4: Super Sudoku Solver CSCI 2101 Fall 2017

Program Correctness and Efficiency. Chapter 2

Another interface: Comparable

c) And last but not least, there are javadoc comments. See Weiss.

Objects and Iterators

CMSC 132: Object-Oriented Programming II

CS 170 Java Programming 1. Week 10: Loops and Arrays

Full file at

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

If you don t, it will return the same thing as == But this may not be what you want... Several different kinds of equality to consider:

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

+ Abstract Data Types

Maps and Trees. CS310: Program 2. 1 Overview. 2 Requirements. Instructor Provided Files. Late Work: Up to 72 hours Penalty: 10% per 24

CS 3114 Data Structures and Algorithms DRAFT Project 2: BST Generic

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

Java Programming Training for Experienced Programmers (5 Days)

CSE 143: Computer Programming II Winter 2019 HW6: AnagramSolver (due Thursday, Feb 28, :30pm)

Chapter 6 Introduction to Defining Classes

Transcription:

CSCI 200 Lab 3 Using and implementing sets In this lab, you will write a program that manages a set of workers, using the Worker hierarchy you developed in Lab 2. You will also implement your own version of an ArraySet class that is similar to the Java set classes. Objectives: to use existing ADTs in the Java Collections Framework to construct and implement a complete ADT to use existing software components to support building new software to gain more insight into using arrays to build data structures Please continue to work with your pair partner(s) on this lab. Work on Problem 1 for the first hour or so of the two-hour lab period. Then move on to Problem 2 to get a good start on it before the lab period is over. Problem 1: Creating a worker application using sets Write a program that manages a set of workers (Set<Worker>) by completing the provided WorkerManager program. Recall that your worker package folder is inside your JavaPackages folder in your home directory, so it will be accessible from this lab folder provided you use an import worker.* statement. Keep the WorkerManager.java in your lab folder outside JavaPackages. We ll be saving Worker objects to an object file so make sure that interface Worker.java in package worker extends Serializable and contains an import java.io.* statement. Note that your worker classes must also correctly override the equals method to compare workers on their names so that you can search for and remove workers by name. In the first part of this lab, you will use one of Java's set ADT implementations called HashSet<E>, which implements the Set<E> interface. Study the interface documentation carefully, as it contains functionalities available to you when using the workers instance variable in the WorkerManager class. You ll need to refer to the class documentation for information on the constructors. The WorkerManager program provides a complete template for your application, but many of the pieces remain to be filled in. These places are all marked with comments in the program. The add method is complete, but it calls three auxiliary (helper) methods: newvolunteer, newhourlyemployee and newsalariedemployee that are not complete. Complete these three methods first as described. Next, partially complete the report method so that it generates a listing containing detailed information on all the workers currently in the workers set. (For now, you do not need to prompt the user for anything, since the method only generates a report containing all workers.) We ll modify this method later on.

At this point you should be able to compile and run the program as it stands. You should be able to add any type of worker and list all the workers in the set. Make sure you have this much working before you go on. Once the add method and the preliminary version of the report method are working, go on to the remove method and complete it. In order to remove a Worker from the workers set, you can use an enhanced for loop (the one with the colon instead of two semi-colons) to find the correct Worker (by name) and then pass the matching object to the set s remove method. If your program produces a ConcurrentModificationException, you should exit from the enhanced for loop using a break statement once you remove the match from the set. Next implement the save and load methods. Note that the HashSet<E> class already implements interface Serializable which allows you to save it to an object file (as you did with a list in the last lab). Finish the WorkerManager program by completing the manage method and the report method as well as any other parts you didn't get done so far. For the report method, use the add method as a template for how to prompt the user for the type of report desired. For any report other than all workers, you will need to iterate through the whole worker set to find the desired workers and report only those that match the search criteria, using the instanceof operator to determine the type of each worker. Allow the user to specify any type from the worker hierarchy including interfaces and abstract classes. The WorkerManager program only manages properties common to all types of workers; specifics related to Volunteers, HourlyEmployees and SalariedEmployees need to be managed separately by their own manager classes. As a result, in order to complete the manage method in class WorkerManager, you need to create three new Java classes: VolunteerManager, HourlyEmployeeManager, and SalariedEmployeeManager. Each of these should be designed to manage a single worker of the specified type with a user interface similar to that of the WorkerManager. Thus, each of the new manager classes will contain an instance field for the Worker object it will manage (for example, the VolunteerManager should have an instance field of type Volunteer) and its constructor will have a parameter for its Worker object field so that all updates are on the original object. In designing the three new classes, consider what types of management are appropriate for each type of worker based on the classes themselves. There will be some overlap, but they won't be the same. The manage method in the WorkerManager program simply creates the appropriate type of manager class and calls it runmanager method.

Problem 2: Implementing your own ArraySet ADT This problem is the first of several in which you will construct your own class implementing an interface either provided to you in the lab folder or stored in the zhstructures package in /usr/people/classes/java, with documentation accessible here. To distinguish your own classes and interfaces from the ones in the zhstructures package, you need to give them their own names and put them in your own package. You ll use your initials to name the package and its associated classes and interfaces. For example, Imad M. Rahal would name his package imrstructures and the class we're constructing today IMRArraySet. Please note that names are case sensitive, package names are (by convention) all lowercase, and interface and class names must start with an uppercase letter. For the rest of this course, when names in the write-up or in files begin with <FOO> or FOO, replace the string with your uppercase initials, and when they begin with <foo> or foo, replace the string with your lowercase initials. Always be consistent about what your initials are. When you re working in a pair, implement the classes in the directories and with the initials of the person doing the typing. The other person can then get copies of these files for their own directories and change the initials in the files and the file names themselves to have the appropriate new initials. Use global find and replace, and be sure to check Case-Sensitive Matching when you make these changes. Create a package directory in your JavaPackages directory with the name of your package (imrstructures in the example case). As you work, be sure to include appropriate Javadoc documentation throughout all class and interface files. (If you re using DrJava, you must have the corresponding class path directories entered; they're probably there already from Lab 1, but if you have problems with DrJava not finding zhstructures or things in your JavaPackages directory, use the procedures in the Lab 1 write-up to set things up. The TA or lab instructor will help you, if necessary.)

Part 2.1: A class that implements the ZHMutableMathSet interface Rename the FOOSetTest.java file with the uppercase initials you are using for your structures (e.g., IMRSetTest), change the import <foo>structures.* statement to your structures package, and again change all instances of <FOO> to the uppercase initials you are using for your structures. Now create a new Java class called <FOO>ArraySet in your <foo>structures directory, using your uppercase initials instead of <FOO>. After any header comments, put a package <foo>structures statement at the top of your class. Next, include import statements for zhstructures.*, java.io.serializable and java.util.*. Add Javadoc class comments and declare the class so it implements the ZHMutableMathSet<ElementType> interface. Be sure to make the class generic by putting the generic parameter <ElementType> immediately after the class name and after the implemented interface name. Next, copy all the methods specified by the ZHMutableMathSet interface to your class, and add a constructor with no parameters and a second constructor with an int parameter called initlength at the beginning of the class body. Implement all the methods as stub methods for now. Methods that return a boolean can all return true for now, the size method can return 0, and the other methods (which return objects) can return null. Constructors need do nothing for now since we have not added any instance variables yet. When you complete these steps, your class should compile without errors, although there may be warnings Now you are ready to start implementing the class.

Part 2.2: Completing the <FOO>ArraySet vlass Let's first consider how to build a set using an array to store its elements. An array has a fixed length, but a mutable set may grow and shrink in size. We'll use an idea similar to the DoubleTank class for this implementation. Think of an array as a tank that can hold objects: its length corresponds to the capacity of the tank; we'll use a size variable, just as the tank used a level variable, to keep track of how many elements are in the set. We'll keep the elements of the set in slots 0 size 1 of the array. To implement this scheme, we'll need two private instance variables an Object[] array elements and an int variable size initialized to 0 along with a public static final int class variable DEFAULT_INIT_LENGTH, initialized to a reasonable power of 2 such as 1024. We'll turn now to implementing the methods needed for the array set. Every class needs at least one constructor; for the array set, we'll make two constructors that both create an empty set. The first will create a set with a capacity (array length) of DEFAULT_INIT_LENGTH; the second will create a set with a capacity (initlength) specified by the user. We can implement the first by having it call the second, passing the default length as the parameter (this(default_init_length);); the second needs to allocate an Object array, cast it to ElementType[] and assign it to the elements instance variable. The size instance variable is already initialized to 0 at its declaration. Users can employ the second constructor when they know the maximum set size in advance or if they want to use a particular initial length; otherwise, they use the first constructor. Since the second constructor has a parameter, you should consider whether there are possible invalid values for the parameter, and if so, the constructor should throw an IllegalArgumentException if the parameter value is not valid. In this case, be sure to document the exception with an @throws tag in your Javadoc comments for the constructor (which, of course, you ve already written). Next, implement the isempty, size and contains methods. These should be straightforward. The contains method must search through the elements of the set until it either finds a match using the equals method or exhausts the elements of the set without finding a match. For the add method, we can put the new element any place we want in the elements array that is part of the contiguous block of elements, but it's easiest to put it at the end of the block. Before adding the new element, however, we need to check whether it's already there (using the contains method). If the element is already in the set, the method should change nothing and return false. Once the method has determined that the element is not already present, it needs to check whether the array is at capacity (the size of the set is equal to the length of the elements array); if so, it calls the private reallocate method described in the next paragraph. Finally, the method stores the new element at index size in the array, increments size and returns true. The reallocate method should be private, since it's a helper method only used internally by the class itself. It should create a new array of Object cast to ElementType[], twice the length of the elements array, and copy all objects from elements into the new array. Once it's done copying elements, it stores the reference to the new array in the elements instance variable and returns. The remove method is a little trickier than add. We need to check whether the element we want to delete is actually there. We could use the contains method to do that, but if it returns

true, we have to go back through a second time to find the position of the element. It would be more efficient to use one loop to do both jobs. Write a private find helper method that works just like contains, except that it returns the index in the array where it found the element instead of true, and 1 instead of false. Call find, and if it returns 1 (indicating that it didn t find the element) you can return false; otherwise, you need to remove the element at that index. One way to remove the element would be to move all the following elements down one cell, but since we don't care about order (we re building a Set after all), there's no need to do all that work. Instead, simply decrement size, replace the element to be removed (you already know its index by now) with the last element (now at position size) in the elements array, set the element at the last position to null, and return true. The get method is a little weird. It takes an ElementType object and returns another ElementType object equal to the first object. Realize, however, that the object returned may not be the same object as the one you re searching with. The code is almost the same as contains or find, but if it finds a matching element at position i, it returns the element at that position, and if it finds no such element, it returns null. Next, we need to consider the iterator method. This method needs to return an object of type Iterator<ElementType> attached to this set; thus, we need a class to create such an object. We ll create an inner class for this purpose; that is, we'll make an Iterator class inside the <FOO>ArraySet class, just before the final right brace character. Here's the shell of the code: private class InnerIterator implements Iterator<ElementType> { private int nextposition; public InnerIterator () { nextposition = 0; public boolean hasnext() { // your code here public ElementType next() { // your code here public void remove() { throw new UnsupportedOperationException(); The constructor sets nextposition to 0. The next method throws a NoSuchElementException if there is no next element; otherwise, it returns the element at nextposition and then increments the nextposition variable. The hasnext method returns true when there are still elements not returned. (How does it determine that from the value of nextposition?) We don't want to support revmoing elements through the iterator, so the remove method throws the specified exception. Back in the outer class, the iterator method should return a new instance of the InnerIterator class by calling its constructor.

The last four methods to consider are the mathematical set operations intersection, difference, union, and subset. These methods must leave both this set and the parameter set unchanged. For the first three methods, start by creating a new empty set that will contain the result such as: ZHMutableMathSet<ElementType> result = new <FOO>ArraySet<ElementType>(); (As always, use your initials instead of <FOO>.) Note that since our class implements the ZHMutableMathSet interface, which ultimately extends the Iterable interface via the ZHCollection interface, you can (and should) use the enhanced for-loop to iterate over the elements in a set. For intersection, iterate through the elements of this set and add those elements that are also contained in otherset to the result. The difference method is very similar to intersection so you should be able to figure out the logic on your own. For the union method, you ll need to iterate through first this set and then otherset, adding all the elements of both to the result; since the add method checks for duplicates, no element will be added twice. Finish these three methods by returning the result set. For subset, iterate through the potentialsubset, and for each of its elements, test whether this set contains the element. If you find an element in the potentialsubset not in this set, return false. If you exit the loop without finding such an element, return true. Debug the code so that it compiles without errors. Part 2.3: Testing the class The file <FOO>SetTest.java is a complete JUnit test class that allows you to test your class once it compiles. If you haven t done so already, rename it with the uppercase initials you are using for your structures (such as IMRSetTest), change the import <foo>structures.*; statement to your structures package, and again change all instances of <FOO> to the uppercase initials you are using for your structures. When you have finished testing and believe your implementation is correct, show it to the lab instructor or the TA.

Problem 3: Using your Set ADT implementation in the worker application Create a copy of your complete WorkerManager program from Problem 1; call it WorkerManagerV2. Make all the necessary changes so that this new WorkerManager program uses the ZHMutableMathSet interface and <FOO>ArraySet ADT in your structures package from Problem 2 instead of the Java Collections Framework Set interface and HashSet ADT. Please note that this will require import statements in WorkerManagerV2 to give it access to zhstructures and your structures package. When you are satisfied that the new version of the worker manager is functioning correctly, show it to the TA or lab instructor. Note that the implementation of the remove method in the worker manager is somewhat inefficient. A better approach would be to use a temporary Worker object equal to the one you want to remove (i.e., one that has the same name): Worker dummy = new Volunteer(name); You can simply pass dummy to the set s remove method, and it will remove a matching worker if it contains one. However, implementing this solution in the original worker manager also requires overriding the hashcode method inherited from the Object class, which is beyond the scope of this lab; we will come back to this topic later on. You can try the new solution in the second worker manager, if you like; it should work there.