Java List Splice splice(List list, int index, int deleteCount)

Here you can find the source of splice(List list, int index, int deleteCount)

Description

Removes n elements found at the specified index.

License

Open Source License

Parameter

Parameter Description
list elements
index index at which we are removing
deleteCount the number of elements we will remove starting at the index

Return

an array of elements that were removed

Declaration

public static <T> List<T> splice(List<T> list, int index, int deleteCount) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2012-2015 Codenvy, S.A.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/*from   ww w  . j  a v  a 2s  .  c om*/
 *   Codenvy, S.A. - initial API and implementation
 *******************************************************************************/

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**
     * Removes n elements found at the specified index.
     *
     * @param list elements
     * @param index
     *         index at which we are removing
     * @param deleteCount
     *         the number of elements we will remove starting at the index
     * @return an array of elements that were removed
     */
    public static <T> List<T> splice(List<T> list, int index, int deleteCount) {
        return spliceImpl(list, index, deleteCount, false, null);
    }

    /**
     * Removes n elements found at the specified index. And then inserts the
     * specified item at the index
     *
     * @param list elements
     * @param index
     *         index at which we are inserting/removing
     * @param deleteCount
     *         the number of elements we will remove starting at the index
     * @param value
     *         the item we want to add to the array at the index
     * @return an array of elements that were removed
     */
    public static <T> List<T> splice(List<T> list, int index, int deleteCount, T value) {
        return spliceImpl(list, index, deleteCount, true, value);
    }

    private static <T> List<T> spliceImpl(List<T> list, int index, int deleteCount, boolean hasValue, T value) {
        List<T> removedArray = new ArrayList<>();
        for (int i = deleteCount; i > 0; i--) {
            T removedElem = list.remove(index);
            removedArray.add(removedElem);
        }

        if (hasValue) {
            list.add(index, value);
        }

        return removedArray;
    }
}

Related

  1. splice(List strings, String separator)
  2. splice(List list1, List list2)