insert method

bool insert(
  1. int index,
  2. E element
)

Insert element in the set at index.

If element is already in the set, false is returned. Otherwise, true is returned.

Implementation

bool insert(int index, E element) {
  // If the element is already in the set, stop here
  if (_values.contains(element)) return false;

  // Store all elements from index 0 (included) to [index] (not included).
  Set<E> prefix = Set<E>();
  for (int i = 0; i < index; i++) prefix.add(_values.elementAt(i));

  // Store all elements from [index] (included) to the end (included too)
  Set<E> suffix = Set<E>();
  for (int i = index; i < _values.length; i++)
    suffix.add(_values.elementAt(i));

  // prefix = [0, 1, 2, ..., index-1]
  // suffix = [index, index+1, ..., length-1]

  // Remove all elements
  _values.clear();

  // Add the prefix
  _values.addAll(prefix);
  // Add the infix ([element])
  bool result = _values.add(element);

  // Listen to the element if asked to and if it is possible
  if (result &&
      _propagateNotification &&
      element != null &&
      element is ChangeNotifier) {
    element.addListener(_propagate);
  }

  // Add the suffix
  _values.addAll(suffix);

  // Notify the listeners
  notifyListeners();

  return true;
}