What is DoubleLinkedQueue.addFirst() in Dart?

The dart:collection library provides advanced collection support for the Dart language. The library contains the DoubleLinkedQueue<E> class, which uses a doubly-linked list to implement the abstract Queue<E> class.

The addFirst() method

The DoubleLinkedQueue<E> class contains the addFirst() method which adds an element to the start of a queue.

A queue is a FIFO (First In First Out) data structure. In a queue, the element that is added first will be deleted first.

The figure below illustrates how the addFirst() method works:

Adding an element to start of queue using addFirst() method

Syntax

The syntax of the addFirst() method is as follows:

void addFirst(E value)

Parameters

  • The addFirst method takes a value of type E as input and adds it to the beginning of the queue.

Return value

addFirst does not return anything and it is a constant-time operation.

Code

The code below shows how the addFirst() method works in Dart:

import 'dart:collection';
void main() {
var monthQueue = DoubleLinkedQueue<String>();
monthQueue.add("February");
monthQueue.add("March");
monthQueue.add("April");
print('Printing Queue Elements');
print(monthQueue);
monthQueue.addFirst("January");
print('Printing Queue Elements');
print(monthQueue);
}

Explanation

  • We create an instance of a DoubleLinkedQueue class of type String.
  • Next we use the add() method to add a few strings to the queue: "February", "March", and "April".
  • Notice that all of the elements are added to the end of the queue, as the queue is a FIFO data structure.
  • We now add "January" to the beginning of the queue with the addFirst() method.
  • We use the print() function of the code library to display the queue elements, and it can be observed that the queue contains "January" at the start.

Free Resources

Attributions:
  1. undefined by undefined