-
Notifications
You must be signed in to change notification settings - Fork 227
/
Queue.kt
70 lines (55 loc) · 1.46 KB
/
Queue.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.codingwithmitch.openapi.business.domain.util
/**
* Kotlin version of a java.util Queue
* https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html
*/
class Queue<T> (list:MutableList<T>){
var items: MutableList<T> = list
fun isEmpty():Boolean = items.isEmpty()
fun count():Int = items.count()
override fun toString() = items.toString()
fun add(element: T){
items.add(element)
}
@Throws(Exception::class)
fun remove(): T {
if (this.isEmpty()){
throw Exception("fun 'remove' threw an exception: Nothing to remove from the queue.")
} else {
return items.removeAt(0)
}
}
fun remove(item: T): Boolean {
return items.remove(item)
}
@Throws(Exception::class)
fun element(): T {
if(this.isEmpty()){
throw Exception("fun 'element' threw an exception: Nothing in the queue.")
}
return items[0]
}
fun offer(element: T): Boolean{
try{
items.add(element)
}catch (e: Exception){
return false
}
return true
}
fun poll(): T?{
if(this.isEmpty()) return null
return items.removeAt(0)
}
fun peek():T?{
if(this.isEmpty()) return null
return items[0]
}
fun addAll(queue: Queue<T>){
this.items.addAll(queue.items)
}
fun clear(){
items.removeAll { true }
// items.clear()
}
}