Here you can find the source of moveBackward(final List
Parameter | Description |
---|---|
T | type of the elements of the list |
list | list whose elements to move |
indices | indices of elements to be moved backward by 1 |
public static <T> boolean moveBackward(final List<T> list, final int[] indices)
//package com.java2s; //License from project: Apache License import java.util.Arrays; import java.util.List; public class Main { /**/*from w ww .j ava 2 s . c o m*/ * Moves elements specified by their indices backward by 1. * * <p> * If the specified indices contains 0, then nothing is moved (the first element cannot be moved backward). * </p> * * <p> * Implementation note: the received indices array might be rearranged. If this is unwanted, pass a copy of the original array. * </p> * * @param <T> type of the elements of the list * * @param list list whose elements to move * @param indices indices of elements to be moved backward by 1 * @return true if moving was performed; false otherwise * * @see #moveForward(List, int[]) */ public static <T> boolean moveBackward(final List<T> list, final int[] indices) { if (indices.length == 0) return false; // Nothing to move // Sort indices and iterate over them upward Arrays.sort(indices); if (indices[0] == 0) return false; // Cannot move backward as the first element is marked to be moved for (final int idx : indices) { final T element = list.get(idx); list.set(idx, list.get(idx - 1)); list.set(idx - 1, element); } return true; } }