ListUtils { public static int shiftItem(List<?> list, int index, int offset) { if (offset == 0 || index < 0) { return 0; } if (offset > 0) { int end = index + offset + 1; if (end > list.size()) { end = list.size(); } Collections.rotate(list.subList(index, end), -1); return end - 1; } else { int start = index + offset; if (start < 0) { start = 0; } Collections.rotate(list.subList(start, index + 1), 1); return start; } }  static int[] toIntArray(List<Integer> intList); static int shiftItem(List<?> list, int index, int offset); static void shiftItemToFront(List<?> list, int index); static void shiftItemToBack(List<?> list, int index); static void shiftItemsAsMuchAsPossible(List<?> list, int[] indexArray, int offset); static void shiftItemsWithFixedDistance(List<?> list, int[] indexArray, int offset);  }
@Test public void testShiftItemNormal() { List<String> list = Arrays.asList("A", "B", "C", "D", "E"); ListUtils.shiftItem(list, 2, 1); Assert.assertArrayEquals(new String[]{"A", "B", "D", "C", "E"}, list.toArray()); ListUtils.shiftItem(list, 2, -1); Assert.assertArrayEquals(new String[]{"A", "D", "B", "C", "E"}, list.toArray()); }
@Test public void testShiftItemOverflow() { List<String> list = Arrays.asList("A", "B", "C", "D", "E"); ListUtils.shiftItem(list, 1, 10); Assert.assertArrayEquals(new String[]{"A", "C", "D", "E", "B"}, list.toArray()); ListUtils.shiftItem(list, 3, -10); Assert.assertArrayEquals(new String[]{"E", "A", "C", "D", "B"}, list.toArray()); }