sublist method

  1. @override
List<E> sublist(
  1. int start, [
  2. int? end
])
override

Returns a new list containing the elements between start and end.

The new list is a List<E> containing the elements of this list at positions greater than or equal to start and less than end in the same order as they occur in this list.

final colors = <String>['red', 'green', 'blue', 'orange', 'pink'];
print(colors.sublist(1, 3)); // [green, blue]

If end is omitted, it defaults to the length of this list.

final colors = <String>['red', 'green', 'blue', 'orange', 'pink'];
print(colors.sublist(3)); // [orange, pink]

The start and end positions must satisfy the relations 0 ≤ startendlength. If end is equal to start, then the returned list is empty.

Implementation

@override
List<E> sublist(int start, [int? end]) {
  end ??= _length;
  if (start < 0 || start > _length || end < 0 || end > _length || start > end) {
    throw RangeError.range(start, 0, _length, 'start');
  }
  final newList = LinkedList<E>();
  _Node<E>? current = _getNodeAt(start);
  for (int i = start; i < end; i++) {
    newList.add(current!.value);
    current = current.next;
  }
  return newList;
}