public Slot insertSlotAt ( final int position , @ NonNull final Slot slot ) { if ( position < 0 || size < position ) { throw new IndexOutOfBoundsException ( "New slot position should be inside the slots list. Or on the tail (position = size)" ) ; } final Slot toInsert = new Slot ( slot ) ; Slot currentSlot = getSlot ( position ) ; Slot leftNeighbour ; Slot rightNeighbour = null ; if ( currentSlot == null ) { // this can happen only when position == size. // it means we want to add the slot on the tail leftNeighbour = lastSlot ; } else { leftNeighbour = currentSlot . getPrevSlot ( ) ; rightNeighbour = currentSlot ; } toInsert . setNextSlot ( rightNeighbour ) ; toInsert . setPrevSlot ( leftNeighbour ) ; if ( rightNeighbour != null ) { // right neighbour is only available for non-last slots rightNeighbour . setPrevSlot ( toInsert ) ; } if ( leftNeighbour != null ) { // left neighbour is only available for not-first slots leftNeighbour . setNextSlot ( toInsert ) ; } if ( position == 0 ) { firstSlot = toInsert ; } else if ( position == size ) { lastSlot = toInsert ; } size ++ ; return toInsert ; }
Inserts a slot on a specified position