Java Collections shuffle()
shuffle() 工作原理是随机置换指定列表元素。有以下两个重载方法:
- Java Collections shuffle(list) 方法
- Java Collections shuffle(list, random) 方法
1 语法
public static void shuffle(List<?> list)
或
public static void shuffle(List<?> list, Random random)
2 参数
list:这是将被改组的列表。
random:它是随机性的来源,用于随机排列列表。
3 返回值
无
4 Collections shuffle()示例1
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.shuffle的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
List<String> list = Arrays.asList("A", "B", "C", "D");
System.out.println("List before Shuffle : "+list);
Collections.shuffle(list);
System.out.println("List after shuffle : "+list);
}
}
输出结果为:
List before Shuffle : [A, B, C, D]
List after shuffle : [D, A, B, C]
5 Collections shuffle()示例2
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.shuffle的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
//Create linked list object
LinkedList<Integer> list = new LinkedList<Integer>();
//Add values in the list
list.add(10);
list.add(-20);
list.add(50);
list.add(90);
list.add(-15);
System.out.println("List before Shuffle : "+list);
Collections.shuffle(list);
System.out.println("List after shuffle : "+list);
}
}
输出结果为:
List before Shuffle : [10, -20, 50, 90, -15]
List after shuffle : [-15, 10, 90, 50, -20]
6 Collections shuffle()示例3
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.shuffle的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
//Create linked list object
LinkedList<Integer> list = new LinkedList<Integer>();
//Add values in the list
list.add(45);
list.add(20);
list.add(55);
list.add(90);
list.add(15);
System.out.println("List before Shuffle = "+list);
//We use Random() to shuffle given list.
Collections.shuffle(list, new Random());
System.out.println("Shuffled List with Random() = "+list);
//We use Random(3) to shuffle given list.
Collections.shuffle(list, new Random(3));
System.out.println("Shuffled List with Random(3) = "+list);
}
}
输出结果为:
List before Shuffle = [45, 20, 55, 90, 15]
Shuffled List with Random() = [15, 45, 20, 90, 55]
Shuffled List with Random(3) = [90, 45, 15, 20, 55]
7 Collections shuffle()示例4
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.shuffle的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
List<String> list = Arrays.asList("one", "two", "three", "four");
System.out.println(list);
Collections.shuffle(list, new Random(2));
System.out.println(list);
}
}
输出结果为:
[one, two, three, four]
[four, two, one, three]
热门文章
优秀文章