Here you can find the source of swap(List
Parameter | Description |
---|---|
list | a parameter |
minIndex | a parameter |
maxIndex | a parameter |
public static <T> List<T> swap(List<T> list, int minIndex, int maxIndex)
//package com.java2s; //License from project: Open Source License import java.util.ArrayList; import java.util.List; public class Main { /**//from w w w . j a v a 2s. c om * Method to swap elements at two indexes * * @param list * @param minIndex * @param maxIndex * @return {@link List<T>} */ public static <T> List<T> swap(List<T> list, int minIndex, int maxIndex) { if (list != null && list.size() > 2 && maxIndex > minIndex) { List<T> updatedList = new ArrayList<>(); T elementAtMinIndex = list.get(minIndex); T elementAtMaxIndex = list.get(maxIndex); for (int i = 0; i < list.size(); i++) { if (i != minIndex && i != maxIndex) { updatedList.add(i, list.get(i)); } else if (i == minIndex) { updatedList.add(i, elementAtMaxIndex); } else if (i == maxIndex) { updatedList.add(i, elementAtMinIndex); } } return updatedList; } return null; } }