How to use the elementAt() method of LinkedHashSet in Dart

Overview

In Dart, the elementAt() method is used to get the element at a specific index of the LinkedHashSet class.

Syntax

E elementAt(int index)
Syntax of elementAt() method

Parameters

This method takes an integer value int as an argument. It represents the index of the element to be retrieved.

Note: The argument must be positive and less than the length of the LinkedHashSet. Otherwise, RangeError is thrown.

Return value

This method returns the element at a specific index of the LinkedHashSet class.

Example

import 'dart:collection';
void main() {
//create a new LinkedHashSet which can have int type elements
LinkedHashSet set = new LinkedHashSet<int>();
// add three elements to the set
set.add(1);
set.add(2);
set.add(3);
print('The set is $set');
print('set.elementAt(0) : ${set.elementAt(0)}');
print('set.elementAt(1) : ${set.elementAt(1)}');
print('set.elementAt(2) : ${set.elementAt(2)}');
try{
print('set.elementAt(3) : ${set.elementAt(3)}');
} catch(e){
print(e);
}
}

Explanation

  • Line 1: We import the collection library.
  • Lines 4–9: We create a new LinkedHashSet object with the name set. Next, we use the add() method to add three elements (1,2,3) to the set object.
  • Line 12: We call the elementAt() method with 0 as an argument. This returns the element at the 0th index.
  • Line 13: We call the elementAt() method with 1 as an argument. This returns the element at the 1st index.
  • Line 14: We call the elementAt() method with 2 as an argument. This returns the element at the 2nd index.
  • Line 17: We call the elementAt() method with 3 as an argument. Since the argument is greater than the length of the set, RangeError is thrown.

Free Resources