Assignment 11, due Apr 22Solutions
Part of
the homework for CS:2820, Spring 2016
|
Assume for the purpose of this problem that class LinkedList has only the following methods: get(int index), set(int index,E element), push(E element), size(E element), clear(), plus one initializer, LinkedList(). files as a starting point for your solution to MP5.
A problem: Give a complete and syntactically correct Java code for class FinalizableList. No comments, but make it readable. (1.0 points)
import java.util.LinkedList; import java.lang.UnsupportedOperationException; class FinalizableListextends LinkedList { boolean finalized = false; public void finalize() { finalized = true; }; public E set( int index, E element ) throws UnsupportedOperationException { if (finalized) throw new UnsupportedOperationException(); return super.set( index, element ); } public void push( E element ) throws UnsupportedOperationException { if (finalized) throw new UnsupportedOperationException(); super.push( element ); } public void clear() throws UnsupportedOperationException { if (finalized) throw new UnsupportedOperationException(); super.clear(); } }
The problem statement did not specify what to do if a user tries to change a finalized list. The above code throws an exception, the particular exception thrown seems appropriate (if verbose), but given the problem statement, turning forbidden operations into no-ops or throwing some other reasonable exception would make sense.
A problem: Give Java code that you could add to your class defined above to define a pair of new methods, setI(int index), and setE(E element), such that a call to o.set(i,e) can be replaced with o.setI(i);o.setE(e). If you have to declare new fields of class FinalizableList to do this, feel free to declare them as needed. (1.0 point)
private int index; public void setI( int i ) { index = i; } public E setE( E element ) throws UnsupportedOperationException { if (finalized) throw new UnsupportedOperationException(); return super.set( index, element ); }
A problem: Rewrite the lightChanges method from Exam 2 problem 3 to use this new framework. (1.0 points)
private void lightChanges( float t ) { direction = (direction + 1) % incoming.size(); Road r = incoming.get( direction ); for (int i = 1; i <= r.waiting; i++) this.pickRoad().entryEvent( t ); r.waiting = 0; class LightChangesEv extends Simultion.Event { void trigger() { StopLight.this.lightChanges( time ) } } LightChangesEv e = new LightChangesEv; e.time = t + interval; Simulator.schedule( e ); }