B4J Code Snippet FIFO queue

I find this quite useful - its a FIFO queue (First-In-First-Out)

Initialize - sets up the queue.
isInitilized - true if initialized false if not
push - add an item to the queue (Always to the end).
pop - return the first item AND remove it from the queue.
peek - return the first item but does not remove it
size - returns the size (item count) in the queue
toArray - returns ALL the items in the queue, but does not remove them.

B4X:
private Sub Class_Globals
    Private fx As JFX
    Private thisQueue As JavaObject
    Private init As Boolean = False
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize
    thisQueue.InitializeNewInstance("java.util.concurrent.ConcurrentLinkedDeque",Null)
    init = True
End Sub

public Sub isInitialized As Boolean
    Return init
End Sub
Public Sub push(o As Object)
        thisQueue.RunMethod("add",Array(o))
End Sub
Public Sub pop As Object
    If size > 0 Then
        Return thisQueue.RunMethod("pop",Null)
    Else
        'if no elements return null
        Return Null
    End If       
End Sub
Public Sub peek As Object
    Return thisQueue.RunMethod("peek",Null)
End Sub
Public Sub size As Int
    Return thisQueue.RunMethod("size",Null)
End Sub
Public Sub toArray As Object()
    Return thisQueue.RunMethod("toArray",Null)
End Sub

Usage:
Dim dq as Dequeue ' or whatever you call this class
...
dq.Initialize ' queue is empty
...
dq.push("hello") ' queue now contains 'hello'
dq.push("one") ' queue now contains 'hello','one'
....
Log(dq.pop) ' will print 'hello' - queue will now contain just 'one'
...
Log(dq.peek) ' will print 'one' BUT queue will still contain 'one'
...
Log(dq.size) ' will print 1 as there is only one item left in the queue

Dim s() As Object = dq.toArray ' s will contain a copy of the items in the queue
...
Dim myList As List = dq.toArray ' myList will now contain a copy of the items in queue
 
Last edited:

LucaMs

Expert
Licensed User
Longtime User
You can do the same easily using a simple List.

push - add an item to the queue (Always to the end).
lstObjects.Add(obj)

pop - return the first item AND remove it from the queue.
Index = lstObjects.Size - 1
Dim Obj As Object = lstObjects.Get(Index)
lstObjects.RemoveAt(Index)
Return Obj

peek - return the first item but does not remove it
Return lstObjects.Get(lstObjects.Size - 1)

size - returns the size (item count) in the queue
Return lstObjects.Size

toArray - returns ALL the items in the queue, but does not remove them.
Dim arrObjects(lstObjects.Size) As Object
For i = 0 to lstObject.Size -1
arrObjects(i) = lstObjects.Get(i)
Next
Return arrObjects
 

Daestrum

Expert
Licensed User
Longtime User
You are correct, but a list isn't guaranteed to work in a concurrent read and write environment. The deque can be written and read by multiple modules/function concurrently.
 
Top