Queue
Anonymous contributor
Published Feb 15, 2024
Contribute to Docs
A queue is a type of collection that supports operations at both ends. Data is added to one end and removed from the other, following a “first in, first out” (FIFO) principle.
Syntax
Creating a queue:
Queue queue_name = new Queue();
We can also create a queue from an existing list:
var queue_name = new Queue.from(list_name);
Note: To use a queue in a Dart program, we have to import the
dart:collection
module. If we don’t do so, then we will see the following error:
Error compiling to JavaScript:
main.dart:6:3:
Error: 'Queue; isn't a type
Queue<String> example_queue = new Queue<String>();
^^^^^
main.dart:6:28:
Error: Method not found: 'Queue'.
Queue<String> example_queue = new Queue<String>();
^^^^^
Error: Compilation failed.
Example
In the following example, a queue is created and elements are inserted in the queue using the .add()
method:
import 'dart:collection';void main(){// Creating a queueQueue<String> example_queue = new Queue<String>();// Printing the default value of example_queueprint(example_queue);// Adding elements to example_queueexample_queue.add("This");example_queue.add("Is");example_queue.add("A");example_queue.add("Queue");// Printing the updated example_queueprint(example_queue);}
The above code will result in the following output:
{}{This, Is, A, Queue}
Queue
- .add()
- Inserts a specified element to the end of a queue.
- .addAll()
- Adds all elements of a collection to the end of a queue.
- .clear()
- A method that removes all elements in the queue.
- .contains()
- Checks if a specified element is present in the queue.
- .length
- Returns the number of elements in a queue.
- .remove()
- Removes the first occurrence of an element from a queue.
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.