/* CookieJarArrayBuffer implementation of the CookieJar ADT in Scala H. Conrad Cunningham Version #1: 15 March 2010 Version #1a: 22 March 2010 Comment correction 123456789012345678901234567890123456789012345678901234567890123456789012345678 */ import scala.collection.mutable._ /* Class CookieJarArrayBuffer implements the CookieJar ADT using Scala's ArrayBuffer data structure to implement the jar (mathematical bag) of cookies. The cookies occur in the Arraybuffer the same number of times they do in the cookie jar. IMPLEMENTATION INVARIANT: (ForAll c : c IN CookieType :: OCCURRENCES(c,Bag) == jar.filter(_==c).length ) */ class CookieJarArrayBuffer[CookieType] extends CookieJar[CookieType] { // CookieJar's bag model is implemented by ArrayBuffer jar. private var jar = new ArrayBuffer[CookieType] def putIn(cookie: CookieType) { jar += cookie } def eat(cookie: CookieType) { val in = jar.indexOf(cookie) if (in >= 0) jar.remove(in) else throw new RuntimeException( "Attempt to eat cookie \"" + cookie + "\", which is not in the jar.") } def isEmpty: Boolean = jar.isEmpty def has(cookie: CookieType): Boolean = jar.contains(cookie) /* Redefine toString to return form "CookieJar(e1,e2,e3,...,en)" with all elements of bag in arbitrary order. */ override def toString = "CookieJar(" + jar.mkString(",") + ")" }