Swaps the elements of list list at indices index1 and index2. @param list the list to manipulate. @param index1 position of the first element to swap with the element in index2. @param index2 position of the other element. @throws
(List<?> list, int index1, int index2)
| 1988 | * @since 1.4 |
| 1989 | */ |
| 1990 | @SuppressWarnings("unchecked") |
| 1991 | public static void swap(List<?> list, int index1, int index2) { |
| 1992 | if (list == null) { |
| 1993 | throw new NullPointerException(); |
| 1994 | } |
| 1995 | final int size = list.size(); |
| 1996 | if (index1 < 0 || index1 >= size || index2 < 0 || index2 >= size) { |
| 1997 | throw new IndexOutOfBoundsException(); |
| 1998 | } |
| 1999 | if (index1 == index2) { |
| 2000 | return; |
| 2001 | } |
| 2002 | List<Object> rawList = (List<Object>) list; |
| 2003 | rawList.set(index2, rawList.set(index1, rawList.get(index2))); |
| 2004 | } |
| 2005 | |
| 2006 | /** |
| 2007 | * Replaces all occurrences of Object {@code obj} in {@code list} with |