...
The Homework Support files IntList.java,
IntListVisitor.java
, LengthVisitor
, ScalarProductVisitor
, and IntListTest.java
provide a starting point for your code. Feel free to edit these files and omit files that are not needed in this homework assignment.
Problems
Apply the visitor design pattern to define visitor classes implementing the IntListVistor
interface IntList
and its subclasses given above to formulate all of the following methods as visitorsJUnit test class, IntListTest
to test all of your new methods in the IntList
class. Use the LengthVisitor example as a guide for defining your new visitor classes. Augment the test clas IntListTest.java
to include test methods for each of your visitor classes. Confine your documentation to writing contracts (purpose statements in HTDP terminology) for each visitor using javadoc
notation (a comment preceding the corresponding definition) beginning with /**
and closing with */
for each visitor class. Use the documentation of LengthVisitor
in the Homework Support files as an example.
- (10 pts.)
boolean contains(int key)
returnstrue
ifkey
is in the list,false
otherwise. Name you visitor classContainsVisitor
.) - (10 pts.)
int reverse()
constructs a list that is the reversal of this. Name your visitor classReverseVisitor
. Hint: this computation is faster and simpler if you introduce a help "method" that takes an argument (also a visitor). - (10 pts.)
int sum()
computes the sum of the elements in the list. Name your visitor class SumVisitor. - (10 pts.)
double average()
computes the average of the elements in the list; returns0
if the list is empty.
Name your visitor classAverageVisitor
. Hint: you can cast anint
todouble
by using the prefix casting operator(double)
. - (10 pts.)
IntList notGreaterThan(int bound)
returns a list of elements in this list that are less than or equal tobound
. Name your visitor classNotGreaterThanVisitor
. - (10 pts.)
IntList remove(int key)
returns a list of all elements in this list that are not equal tokey
. .Name your visitor class RemoveVisitor - (10 pts.)
IntList subst(int oldN, int newN)
returns a list of all elements in this list witholdN
replaced bynewN
. Name your visitor class SubstVisitor - (15 pts.)
IntList merge(IntList other)
merges this list with the input list other, assuming that this list and other are sorted in ascending order. Note that the lists need not have the same length.
. Name your visitor classMergeVisitor
. Hint: add a method "method"mergeHelp(ConsIntList other)
that does all of the work if one list is non-empty (aConsIntList
). OnlymergeHelp
is recursive. Use dynamic dispatch on the list that may be empty. Recall thata.merge(b)
is equivalent tob.merge(a)
. You can formulate help methods as visitors. - (15 pts.)
IntList mergeSort()
. Leveraging themerge
"method" you just wrote (as a visitor), writemergeSort()
that sorts anIntList.
Recall that you need to write a help function that splits a list approximately in two.