Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

linkedlist
clear
dart
communitycreator

How to remove the elements of LinkedList in Dart

Programming Bytes

In Dart, LinkedList is a specialized double-linked list of elements. We use the clear method to remove all the elements present in the LinkedList. After calling this method, the length of the LinkedList becomes zero.

Note: LinkedList is not a list implementation but only accepts elements that extend the LinkedListEntry class.

Syntax

void clear()

Note: This method doesn’t take any argument, or return any value.

Example

The code below demonstrates how to remove all elements present in the LinkedList:

import 'dart:collection';
class Entry<T> extends LinkedListEntry<Entry<T>> {
  T value;
  Entry(this.value);
  @override
  String toString() {
    return '$value';
  }
}

void main() {
  // create a list
  var linkedList = LinkedList<Entry<int>>();
  // add two element to the list
  linkedList.add(Entry(10));
  linkedList.add(Entry(20));
  print("linkedList is : $linkedList");
  // delete all elements on the list
  linkedList.clear();
  print("After calling clear, The linkedList is : $linkedList");
}
Using clear method to remove all elements of the LinkedList

Explanation

  • Line 1: We import the collection library.

  • Lines 2–9: We create a class Entry that extends the LinkedListEntry class. We add a dynamic value variable and a constructor for the Entry class. This variable overrides the toString method to return the value of the current element.

  • Line 13: We create a new LinkedList object with the name linkedList.

  • Lines 15 and 16: We create two objects for the Entry class and add them to the linkedList object using the add method.

  • Line 19: We use the clear method to delete all the elements of the linkedList. After calling this method, the linkedList becomes empty.

RELATED TAGS

linkedlist
clear
dart
communitycreator
RELATED COURSES

View all Courses

Keep Exploring