java中List集合中任意兩個位置的資料互相調換
阿新 • • 發佈:2019-02-13
程式碼有問題,請直接看1樓的評論,就不更改或刪除文章啦
import java.util.ArrayList;
public class ListDemo {
/**
* List原始碼方法:public void add(int location, E object);
* 思路:
* 呼叫這個方法後,原來的location位置上的值會往後移動一位(原location後的資料對應往後移一位)
* 那麼就要移除原location移動後的位置上的資料
*/
public static void main(String[] args) {
ArrayList<String> strList = new ArrayList<>();
strList.add("序列1");
strList.add("序列2");
strList.add("序列3");
strList.add("序列4");
strList.add("序列5");
// 測試:序列2與序列5對調
int replaceNum1 = 1;
int replaceNum2 = 4;
strList.add(replaceNum1, strList.get(replaceNum2));
strList.add(replaceNum2+1, strList.get(replaceNum1+1));
strList.remove(replaceNum1+1);
strList.remove(replaceNum2+1);
System.out.println(strList.toString());
}
}