# Queue (Data Structure) ###### tags: `Data Structure` `Queue` `FIFO` [TOC] # Introduction A **Queue** us a FIFO(First In First Out) Structure. Whatever goes inside first, it will be the first one to go out/remove also. **Note:** **Enqueue** states for insert. **Dequeue** states for remove. **FIFO Explanation Image:** ![](https://i.imgur.com/fBjMGSg.png) # Dequeue Action: Poll V.S Remove Both **poll()** and **remove()** takes the first item in the queue and takes the item out. But what is the difference? The only differ on what they return if **the Queue is empty**. Remove will throw **NoSuchElementException**, while poll returns a **null**. # Check First Item: Peek V.S Element Both **peek()** and **element()** checks what the first item is at the queue. But same as poll and remove, they only differ on what they return when queue is empty. **Peek will return null**, while **element throws NoSuchElementException**. # Reference https://bezkoder.com/kotlin-queue/ # Queue small example: This is just a small Queue that deals animations coming in. Due to Customer request, it has to be shown in order and can be interrupt whenever it wants. Therefore, this class was written. As we can see, to instantiate a Queue we use LinkedList. ```kotlin= import android.util.Log import java.util.* class AnimQueueHelper { private val animQueue : Queue<String> = LinkedList<String>() private var isRun : Boolean = false fun needAnimStart() : Boolean{ val needStart : Boolean = isQueueAvailable() && !checkRunStatus() Log.d("ANIM_CHECK", "needStart ${needStart} == isQueueAvailable() ${isQueueAvailable()} !checkRunStatus() ${!checkRunStatus()} " ) startRun() return needStart } fun checkRunStatus() : Boolean{ return this.isRun } fun isQueueAvailable() : Boolean{ return this.animQueue.size > 0 } fun addQueue(animJson : String){ val url = UrlHelper.checkHttps(animJson) this.animQueue.add(url) Log.d("ANIM_CHECK", this.animQueue.toString()) } fun dealNextAnim() : String{ Log.d("ANIM_CHECK", "dealNextAnim: " + this.animQueue.toString()) val animDisplay = this.animQueue.peek()?:"" this.animQueue.poll() return animDisplay } fun stopRun() = dealRun(false) private fun startRun() = dealRun(true) private fun dealRun(isRun : Boolean){ this.isRun = isRun } } ```