Java Collections swap()

swap() 用于交换指定列表中指定位置的元素。

1 语法

public static void swap(List<?> list, int i, int j)  

2 参数

list:这是我们将交换元素的列表。

i:它是要交换的一个元素的索引。

j:它是要交换的其他元素的索引。

3 返回值

4 Collections swap()示例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.swap的例子
 */
import java.util.*;

public class Demo {

    public static void main (String[] args) {
        //Create a list with items
        ArrayList<String>  list = new ArrayList<String>();
        list.add("Java");
        list.add("Android");
        list.add("Python");
        list.add("Node.js");
        System.out.println("Original List : " +list);
        //Perform swapping
        Collections.swap(list, 0, 2);
        System.out.println("List after swapping : " +list);
    }
}

输出结果为:

Original List : [Java, Android, Python, Node.js]
List after swapping : [Python, Android, Java, Node.js]

5 Collections swap()示例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.swap的例子
 */
import java.util.*;

public class Demo {

    public static void main (String[] args) {
        //Create a list with items
        List<Integer> list = Arrays.asList(44, 55, 99, 77, 88, 66);
        System.out.println("List before swapping: "+list);
        Collections.swap(list, 2, 5);
        System.out.println("List after swapping: "+list);
    }
}

输出结果为:

List before swapping: [44, 55, 99, 77, 88, 66]
List after swapping: [44, 55, 66, 77, 88, 99]

6 Collections swap()示例3

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.swap的例子
 */
import java.util.*;

public class Demo {

    public static void main (String[] args) {
        //Create a list with items
        List<Integer> list = Arrays.asList(44,55,99,77,88,66,33,22);
        System.out.println("List before swapping: "+list);
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter index i : ");
        int i = sc.nextInt();
        System.out.print("Enter index j : ");
        int j = sc.nextInt();
        Collections.swap(list, i, j);
        System.out.println("List after swapping: "+list);
        sc.close();
    }
}

输出结果为:

List before swapping: [44, 55, 99, 77, 88, 66, 33, 22]
Enter index i : 3
Enter index j : 6
List after swapping: [44, 55, 99, 33, 88, 66, 77, 22]

 

热门文章

优秀文章