Vous êtes sur la page 1sur 15

!"#!

%&'
!"#$%& ()*"% +,"# -.&/0)1*/ " !"#$%&"'
!"#$% '('# %)*#+ ,-".% looking at these solutions until you've put significant effoit
into ueveloping youi own solution to these pioblems!!!


/01 Biaw an intia-methou contiol flow uiagiam foi the !"#$%"!&# &#$(!)* of the methou:
MyListNode<E> find(int index) throws IllegalIndexPosition;
in the ubc.cpsc210.list.linkedList.MyLinkedList class of the pioject
\lectures\LinkedListComplete



/2,3 What uoes it mean foi the uesign of a class to be iobust.

4*56%7 ,88 "9 %)' :'%)";6 *# %)' <8,66 :.6% -' 5"-.6%1 = :'%)"; *6 5"-.6% *9 *%6
6>'<*9*<,%*"# <"('56 ,88 >"66*-8' *#>.% (,8.'6 %" %),% :'%)";1

?# ,;;*%*"#7 @' :.6% 6>'<*9A <8,66 *#(,5*,#%6 ,#; '#6.5' %),% %)'A )"8; -'9"5'
,#A :'%)"; *# %)' <8,66 *6 <,88'; ,#; *::';*,%'8A ,9%'5 ,#A "9 %)"6' :'%)";6
'B'<.%'61 C)' *#(,5*,#%6 6>'<*9A @),% ,# ">'5,%*"# <,# ,66.:' ,-".% %)'
6%,%' "9 ,# *#6%,#<' "9 %),% <8,66 ,% ,#A %*:'1

-3 Besign anu implement a class that iepiesents an +*,-#,.#/ exception that will be
thiown by the following methou of a MyArrayList<E> class when the inuex is not
valiu:
public E get(int index);
The class must pioviue a constiuctoi that takes the invaliu inuex as a paiametei anu
uses it to constiuct a meaningful eiioi message that can be uisplayeu when the
exception is caught.

/**
* Represents an exception raised when an illegal index
* is used.
*/
public class IllegalIndexPosition extends RuntimeException {
/**
* Constructor
* @param index the illegal index
*/
public IllegalIndexPosition(int index) {
super("The index " + index + " is not valid.");
}
}






/D1 Suppose that a fiienu of youis has uesigneu a type hieiaichy wheie ClassB is a
subclass of ClassA. ClassB oveiiiues the methou doSomething uefineu in ClassA
anu thiows a checkeu exception that is not thiown by the methou in ClassA. The
coue uoes not compile. In teims of a uesign piinciple stuuieu this teim, explain why
you woulu not want such coue to compile.

E'<,88 %),% @' @,#% %" -' ,-8' %" 6.-6%*%.%' ,# *#6%,#<' "9 %)' 6.-<8,66 9"5 ,#
*#6%,#<' "9 %)' 6.>'5 <8,661 F' @".8; #"% @,#% %)' <";' ;'6<5*-'; ,-"(' %"
<":>*8' -'<,.6' *9 @' @'5' %" 6.-6%*%.%' ,# *#6%,#<' "9 ClassB 9"5 ,# *#6%,#<'
"9 ClassA %)' :'%)"; doSomething :*G)% %)5"@ , <)'<+'; 'B<'>%*"# %),% %)'
<8*'#% @,6 #"% 'B>'<%*#G1


/H1 This question iefeis to the class ubc.cpsc210.list.linkedList.MyLinkedList
fiom the \lectures\LinkedListComplete pioject.

Complete the implementation of the following membei of the
linkedlist.MyLinkedList class. Assume that Collection<E> is fiom the java.util
package.

/**
* Returns true if this list contains all the elements in the
* collection c, false otherwise.
*/
public boolean containsAll(Collection<E> c) {
for (E next : c) {
if (!contains(next))
return false;
}

return true;
}



/I1 Pioviue an implementation foi the classes shown in the 0NL uiagiam below. You
must incluue any fielus oi methous necessaiy to suppoit the ielationship between
the classes in auuition to appiopiiate getteis anu setteis. Note that a ioute has two
associateu aiipoits: the uepaituie aiipoit anu the aiiival aiipoit. Each aiipoit has a
unique coue (e.g. "YvR" iepiesents vancouvei Inteinational, "LBR" iepiesents
Lonuon Beathiow anu "PEK" iepiesents Beijing) which cannot be changeu.

Assume that once set, the aiiival anu uepaituie aiipoits foi a paiticulai ioute
cannot be changeu. Fuithei assume that ioutes can be auueu to oi iemoveu fiom a
flight map but the same ioute cannot be auueu to the flight map moie than once.
We consiuei two ioutes to be the same if they have the same uepaituie anu aiiival
aiipoits. Two aiipoits aie the same if they have the same coue.




public class Airport {
private final String code;

public Airport(String code) {
this.code = code;
}

public String getCode() {
return code;
}

// Generate these methods using Eclipse!
@Override
public boolean equals(Object o) {
if (o == null)
return false;

if (this.getClass() != o.getClass())
return false;

Airport other = (Airport) o;

return (code.equals(other.code));
}

@Override
public int hashCode() {
return code.hashCode();
}
}


public class Route {
private final Airport departure;
private final Airport arrival;

public Route(Airport dep, Airport arr) {
departure = dep;
arrival = arr;
}

public Airport getDepartureAirport() {
return departure;
}

public Airport getArrivalAirport() {
return arrival;
}

// Generate these methods with Eclipse!
@Override
public boolean equals(Object o) {
if (o == null)
return false;

if (this.getClass() != o.getClass())
return false;

Route other = (Route) o;

return (other.arrival.equals(this.arrival)
&& other.departure.equals(this.departure));
}

@Override
public int hashCode() {
return arrival.hashCode() * 13
+ departure.hashCode();
}
}


public class FlightMap {
private Set<Route> routes;

public FlightMap() {
routes = new HashSet<Route>();
}

public void addRoute(Route r) {
routes.add(r);
}

public void removeRoute(Route r) {
routes.remove(r);
}
}

/J1 Foi each of the scenaiios below, iuentify which collection fiom the }ava Collections
Fiamewoik you woulu use anu biiefly justify youi answei.

,3 Suppose you want to simulate line-ups at a bank. Theie can be anywheie fiom
one to seveial telleis available at any given time anu each tellei has theii own
line-up of customeis. Telleis aie numbeieu sequentially staiting at position u.
You want to be able to get the line-up foi a paiticulai tellei station by
specifying the tellei's position numbei. If the tellei at position 2, foi example,
is absent, the line-up is null. Assume that theie is a Customer class in the
system. Bow woulu you iepiesent the collection of line-ups.

ArrayList<LinkedList<Customer>>

K,<) 8*#'L.> "9 <.6%":'56 <,# -' 5'>5'6'#%'; -A , LinkedList<Customer>
@)*<) :,*#%,*#6 '#%5*'6 *# 4*56%L?# 4*56%LM.% N4?4M3 "5;'51 F' .6' ,
LinkedList -'<,.6' *% :,+'6 *% ',6*'5 %" 5':"(' %)' <.6%":'5 ,% %)' 6%,5%
"9 %)' 8*6%1 O*('# %),% @' ),(' :"5' %),# "#' 8*#'L.> ,#; %),% @' @,#% %"
),(' >"6*%*"#,8 ,<<'66 %" %)' <"88'<%*"# "9 8*#'L.>67 @' <)""6'
ArrayList<LinkedList<Customer>>1 F' <,##"% .6'
Set<LinkedList<Customer>> ,6 , Set ;"'6 #"% >5"(*;' >"6*%*"#,8 ,<<'661
F)'# <)""6*#G , >,5%*<.8,5 *:>8':'#%,%*"# "9 List7 @' G" @*%)
ArrayList ,6 %)' %"%,8 #.:-'5 "9 %'88'5 6%,%*"#6 *6 #"% 8*+'8A %" <),#G'
"9%'#1


-3 Suppose you aie uesigning a couise iegistiation system. Assume that theie is a
Student anu a Course class in the system. Bow woulu you stoie the stuuents
anu couises so that you can quickly ietiieve the couises in which a given
stuuent is iegisteieu.

Map<Student, Set<Course>> "5 HashMap<Student, HashSet<Course>>

4"5 ',<) 6%.;'#% @' @,#% %" -' ,-8' %" P.*<+8A 5'%5*'(' %)' <".56'6 *#
@)*<) )'Q6)' *6 5'G*6%'5';1 F' %)'5'9"5' .6' , :,> @*%) %)' 6%.;'#% ,6
+'A ,#; %)' <".56'6 *# @)*<) %)' 6%.;'#% *6 5'G*6%'5'; ,6 %)'
<"55'6>"#;*#G (,8.'1 O*('# %),% , 6%.;'#% @"#$% 5'G*6%'5 *# , <".56'
:"5' %),# "#<' ,% ,#A G*('# %*:'7 @' 5'>5'6'#% %)' <"88'<%*"# "9 <".56'6
.6*#G , Set1








/R1 You have been askeu to altei the lectures/PhotoAlbumBase system to make it
possible foi a methou containing the following coue to compile anu execute
coiiectly:

Album anAlbum = new Album("My Album");
// Put lots of photos into album
//
for (Photo p: anAlbum) {
// do something with each photo
}

Foi each inteiface, class, fielu oi methou that must be changeu oi auueu, uesciibe
the change oi auuition in as close to coiiect }ava syntax as you can.

C)' <8,66 ;'<8,5,%*"# :.6% <),#G'S

public class Album implements Iterable<Photo> {

F' :.6% ,;; %)' :'%)"; *%'5,%"5 %" AlbumT

public Iterator<Photo> iterator() {
return photos.iterator();
}


/U1 You have been given a class ConsoleWriter that can wiite a given stiing to
the console.

public class ConsoleWriter {

private writeToConsole(String s) {
System.out.println(s); }
}

You have been askeu to altei the functionality of the lectures/PhotoAlbumBase
system to wiite to the console the name of any photo auueu oi ueleteu fiom an
album in the system. You have been tolu you must use the 0bseivei uesign pattein
to implement this new functionality.

,3 Biaw a 0NL class uiagiam that pioviues an oveiview of the changes anu auuitions
neeueu to PhotoAlbumBase to suppoit the use of the 0bseivei uesign pattein to
pioviue the uesiieu functionality. You neeu not iepiouuce the entiie 0NL class
uiagiam foi the system. }ust show those paits of the 0NL class uiagiam that must
change. Inuicate fielus anu methous that must be changeu oi auueu in the 0NL
class uiagiam.


-3 Foi each inteiface, class, fielu oi methou that must be changeu oi auueu, uesciibe
the change oi auuition in as close to coiiect }ava syntax as you can.

1) ?:>8':'#% M-6'5(,-8'1

public class Observable {

List<Observer> observers;

public Observable() {
observers = new ArrayList<Observer>();
}

public void addObserver(Observer o) {
observers.add(o);
}

public void notifyObservers(String s) {
for (Observer o: observers)
o.update(s);
}
}


2) ?:>8':'#% M-6'5('51

public interface Observer {
public abstract void update(String s);
}


3) !'<8,5,%*"# "9 =8-.: :.6% <),#G'S

public class Album extends Observable {


4) =8-.:V6 <"#6%5.<%"5 :.6% <),#G' %" *#<8.;'S

public Album() {

ConsoleWriter cw = new ConsoleWriter();
addObserver(cw);
}


5) W),#G' W"#6"8'F5*%'5V6 ;'<8,5,%*"#S

public class ConsoleWriter implements Observer {



6) X.6% ,8%'5 ,;;Y)"%"NT3 ,#; 5':"('Y)"%"NT3 %" ,;; #"%*9*<,%*"# %"
"-6'5('56S

public void addPhoto(Photo p) {

notifyObservers(p.getName());
}

public void removePhoto(Photo p)

notifyObserver(p.getName());
}

7) X.6% >5"(*;' *:>8':'#%,%*"# 9"5 .>;,%' "# W"#6"8'F5*%'5S

public void update(String s) {
writeToConsole(s);
}





/Z1 Consiuei the following }ava class.

public class Clock {
private Integer startTime;
private Integer numHours;

public Clock( Integer start, Integer hrs ) {
startTime = start;
numHours = hrs;
}
}

Nouify this class anu intiouuce any othei coue iequiieu, but without using any
stanuaiu }ava Collection Fiamewoik classes oi inteifaces (e.g., List), so that you can
iteiate ovei an instance of Clock using a foi-each loop. Foi example, the following
coue shoulu piint the numbeis 2, S, 4, anu S. You uo not have to consiuei the case
wheie the houis go past 2S. Assume the input you'ie given will piouuce output
within the same uay (i.e., values between u-2S only).

for (Integer i: new Clock(2,4)) {
System.out.println(i);
}



import java.util.Iterator;

public class Clock implements Iterable<Integer> {

private Integer startTime;
private Integer numHours;

public Clock(Integer start, Integer hrs) {
startTime = start;
numHours = hrs;
}

@Override
public Iterator<Integer> iterator() {
return new ClockIterator();
}

private class ClockIterator implements Iterator<Integer> {

private int currTime;

public ClockIterator(){
currTime = startTime;
}

@Override
public boolean hasNext() {
return currTime < (startTime + numHours);
}

@Override
public Integer next() {
Integer nextTime = currTime;
currTime++;
return nextTime;
}

@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}



/0[ Suppose you aie uesigning an Anuioiu app that will allow the usei to peifoim task
management. The usei can auu tasks to the system anu can gioup tasks togethei
into piojects. Piojects can be auueu as sub-piojects of othei piojects, nesteu
aibitiaiily ueep. Each task has an estimateu time foi completion that is specifieu
when the task is constiucteu. You want to be able to tieat inuiviuual tasks anu
piojects in the same way. In paiticulai, you want to be able to get the time neeueu
to complete a task oi a pioject. The time taken to complete a pioject is the total
time neeueu to complete all the tasks in the pioject oi in sub-piojects of that pioject.

,3 Consiuei the paitially completeu coue in the TaskManager pioject. Biaw a 0NL
uiagiam that incluues all the classes in the ca.ubc.cpsc210.taskmanager.model
package anu that shows how you will apply the composite pattein to the uesign of
this system.


-3 Wiite the complete implementation of the Task anu Project classes below. Note
that all the tests pioviueu in
ca.ubc.cpsc210.taskmanager.tests.TestProject shoulu pass. Space is also
pioviueu on the following page foi youi answei to this question.



public class Task extends WorkUnit {
private int hours;

public Task(int hours) {
this.hours = hours;
}

public int hoursToComplete() {
return hours;
}
}



abstract
WorkUnit
Task Project
*
public class Project extends WorkUnit {
private List<WorkUnit> units;

public Project() {
units = new ArrayList<WorkUnit> units;
}

public void add(WorkUnit wu) {
units.add(wu);
}

public int hoursToComplete() {
int total = 0;

for( WorkUnit wu : units )
total += wu.hoursToComplete();

return total;
}
}


/001 The following 0NL class uiagiam iepiesents the uesign of a "TicketWizaiu" system
that allows tickets to be solu foi uiffeient events helu at venues acioss the countiy.


Answei the following questions baseu on the uesign piesenteu in the 0NL uiagiam
above anu #"% on what you think the uesign shoulu be! Ciicle C5.' oi 4,86' anu
biiefly explain youi choice. Note that you will eain no maiks if youi explanation is
not coiiect.

,3 Tiue oi False: given a customei object, you can ietiieve the oiueis placeu by that
customei.

4,86'S %)' 8*#+ -'%@''# M5;'5 ,#; W.6%":'5 *6 .#*L;*5'<%*"#,8 95": M5;'5 %"
W.6%":'51


Venue Event
SeatingPlan Section Seat
Order
Ticket
Customer
1
*
1 1
*
1
1..* 1..*
1
-3 Tiue oi False: it is possible that an oiuei has no tickets associateu with it.

C5.'S %)' :.8%*>8*<*%A "# %)' M5;'5 '#; *6 \7 :',#*#G [ "5 :"5'1


<3 Tiue oi False: given a ticket object, it is possible to ietiieve the section object to
which the associateu seat belongs.

C5.'S A". <,# G'% %)' <"55'6>"#;*#G 6',% ;*5'<%8A ,#; %)' 6'<%*"# (*, %)' -*L
;*5'<%*"#,8 ,66"<*,%*"# -'%@''# ]',% ,#; ]'<%*"#1





/021 This question iefeis to the lectures/CompositeDrawingEditorComplete
pioject. Note that a Drawing stoies the figuies uiawn by the usei in a list in the
oiuei in which they weie uiawn. In this question you must assume that the usei
has uiawn thiee figuies in the oiuei listeu heie: a iectangle, an ellipse anu a squaie.
Now assume that the usei chooses the "select" tool anu clicks the ellipse figuie. In
so uoing, the ellipse figuie changes fiom "not selecteu" to "selecteu".

Biaw a (#0+#*,# /!%1$%2 foi the methou
SelectionTool.mousePressedInDrawingArea, calleu as a iesult of the usei
clicking the ellipse figuie with the "select" tool. It is not necessaiy to incluue calls to
any methous in the }ava libiaiy. 0se the fact that you know which figuies have been
uiawn to iesolve calls to abstiact methous. If you encountei a bianch in the coue, it
is necessaiy to incluue only those methous that will actually execute in the scenaiio
uesciibeu above. You may abbieviate the names of types anu methous pioviueu you
uo not intiouuce any ambiguity into youi uiagiam.


s
t
:
S
T
m
o
u
s
e
P
r
e
s
s
e
d
I
n
D
A
e
d
i
t
o
r
:
D
E
g
e
t
F
i
g
u
r
e
I
n
D
c
u
r
r
e
n
t
D
r
a
w
i
n
g
:
D
g
e
t
F
i
g
u
r
e
A
t
P
f
i
g
u
r
e
:
R
c
o
n
t
a
i
n
s
f
i
g
u
r
e
:
E
c
o
n
t
a
i
n
s
i
s
S
e
l
e
c
t
e
d
s
e
l
e
c
t
S
T

:

S
e
l
e
c
t
i
o
n
T
o
o
l
D
E

:

D
r
a
w
i
n
g
E
d
i
t
o
r
D


:

D
r
a
w
i
n
g
R


:

R
e
c
t
a
n
g
l
e
E


:

E
l
l
i
p
s
e

Vous aimerez peut-être aussi