code: private int extractValidIndex(ElementReference ref) {
          Reference<E> iRef = asIndexedRef(ref);
          int idx = iRef.index;
          if (idx < 0 || idx >= size) {
              throw new InvalidReferenceException(
                      "Index " + idx + " is not valid for collection with size " + size + ".");
          }
          return idx;
      }
docs: Convenience method for extracting the index stored in an ElementReference, and throws a more specific exception
  if the cast fails or the index is not valid.