Java tutorial
//package com.java2s; /* * Copyright 2004-2014 the Seasar Foundation and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ import java.util.ArrayList; import java.util.List; public class Main { public static <ELEMENT> List<ELEMENT> moveElementToIndex(List<ELEMENT> list, ELEMENT fromElement, ELEMENT toElement) { assertObjectNotNull("list", list); final int fromIndex = list.indexOf(fromElement); final int toIndex = list.indexOf(toElement); return moveElementToIndex(list, fromIndex, toIndex); } public static <ELEMENT> List<ELEMENT> moveElementToIndex(List<ELEMENT> list, int fromIndex, int toIndex) { assertObjectNotNull("list", list); if (fromIndex == toIndex) { String msg = "The argument 'fromIndex' and 'toIndex' should not be same:"; msg = msg + " fromIndex=" + fromIndex + " toIndex" + toIndex; throw new IllegalArgumentException(msg); } if (fromIndex < 0 || toIndex < 0) { String msg = "The argument 'fromIndex' and 'toIndex' should not be minus:"; msg = msg + " fromIndex=" + fromIndex + " toIndex" + toIndex; throw new IllegalArgumentException(msg); } final boolean fromLess = fromIndex < toIndex; final List<ELEMENT> movedList = new ArrayList<ELEMENT>(); final int firstIndex = fromLess ? fromIndex : toIndex; final int secondIndex = !fromLess ? fromIndex : toIndex; final List<ELEMENT> first = list.subList(0, firstIndex); final ELEMENT element = list.get(fromIndex); final int adjustmentIndex = fromLess ? 1 : 0; final List<ELEMENT> middle = list.subList(firstIndex + adjustmentIndex, secondIndex + adjustmentIndex); final List<ELEMENT> last = list.subList(secondIndex + 1, list.size()); movedList.addAll(first); if (!fromLess) { movedList.add(element); } movedList.addAll(middle); if (fromLess) { movedList.add(element); } movedList.addAll(last); return movedList; } protected static void assertObjectNotNull(String variableName, Object value) { if (variableName == null) { String msg = "The value should not be null: variableName=null value=" + value; throw new IllegalArgumentException(msg); } if (value == null) { String msg = "The value should not be null: variableName=" + variableName; throw new IllegalArgumentException(msg); } } }