shift Item in List - Java java.util

Java examples for java.util:List Operation

Description

shift Item in List

Demo Code


//package com.java2s;

import java.util.List;

public class Main {
    public static <T> void shiftItem(List<T> list, T item, int toIndex) {
        int oldIndex = list.indexOf(item);
        if (oldIndex < 0) {
            throw new IllegalArgumentException("Item not found");
        }/*from w w  w .j ava  2s  . com*/
        if (toIndex >= 0 && toIndex < list.size()) {
            list.remove(oldIndex);
            list.add(toIndex, item);
        } else {
            throw new IndexOutOfBoundsException("Index out of bounds: "
                    + toIndex + " (list size = " + list.size() + ")");
        }
    }
}

Related Tutorials