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,RangeErroris 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 elementsLinkedHashSet set = new LinkedHashSet<int>();// add three elements to the setset.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
collectionlibrary. - Lines 4–9: We create a new
LinkedHashSetobject with the nameset. Next, we use theadd()method to add three elements (1,2,3) to thesetobject. - Line 12: We call the
elementAt()method with0as an argument. This returns the element at the 0th index. - Line 13: We call the
elementAt()method with1as an argument. This returns the element at the 1st index. - Line 14: We call the
elementAt()method with2as an argument. This returns the element at the 2nd index. - Line 17: We call the
elementAt()method with3as an argument. Since the argument is greater than the length of theset,RangeErroris thrown.