Created
September 25, 2020 12:44
-
-
Save tomatophobia/3f1741978ae12a9d173c5d4622caa214 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BoundedSet2[T] { | |
val data: util.LinkedList[T] = new util.LinkedList[T]() | |
var capacity: Int = 0 | |
def BoundedSet(capacity: Int) { | |
this.capacity = capacity; | |
} | |
def add(elem: T) { | |
if (elem==null) throw new NullPointerException() | |
data.remove(elem); | |
if (data.size() == capacity) { | |
data.removeFirst(); | |
} | |
data.addLast(elem); | |
} | |
def contains(elem: T): Boolean = { | |
data.contains(elem); | |
} | |
} | |
object BoundedSetTestsScala { | |
val set: BoundedSet[Int] = new BoundedSet[Int](3) | |
def main(args: Array[String]): Unit = { | |
testSingleElement | |
testRepeatedElement | |
testOverflowKeepsSecond | |
testOverflowRemovesOldest | |
testOverflowKeepsNewest | |
testRenewal | |
} | |
def testSingleElement { | |
set.add(1); | |
assert(set.contains(1)); | |
} | |
def testRepeatedElement { | |
set.add(1); | |
set.add(1); | |
set.add(1); | |
set.add(1); | |
assert(set.contains(1)); | |
} | |
def testOverflowKeepsSecond { | |
set.add(1); | |
set.add(2); | |
set.add(3); | |
set.add(4); | |
assert(set.contains(2)); | |
} | |
def testOverflowRemovesOldest { | |
set.add(1); | |
set.add(2); | |
set.add(3); | |
set.add(4); | |
assert(!set.contains(1)); | |
} | |
def testOverflowKeepsNewest { | |
set.add(1); | |
set.add(2); | |
set.add(3); | |
set.add(4); | |
assert(set.contains(4)); | |
} | |
def testRenewal { | |
set.add(1); | |
set.add(2); | |
set.add(1); | |
set.add(3); | |
set.add(4); | |
assert(set.contains(1)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment