java.util.Collections.shuffle()是java.util.Collections类方法。
// Shuffles mylist public static void shuffle(List mylist) This method throws UnsupportedOperationException if the given list or its list-iterator does not support the set operation.
// Java program to demonstrate working of shuffle()
import java.util.*;
public class GFG
{
public static void main(String[] args)
{
ArrayList<String> mylist = new ArrayList<String>();
mylist.add("code");
mylist.add("quiz");
mylist.add("geeksforgeeks");
mylist.add("quiz");
mylist.add("practice");
mylist.add("qa");
System.out.println("Original List : \n" + mylist);
Collections.shuffle(mylist);
System.out.println("\nShuffled List : \n" + mylist);
}
}
输出:
Original List : [code, quiz, geeksforgeeks, quiz, practice, qa] Shuffled List : [qa, quiz, practice, code, quiz, geeksforgeeks]
它使用用户提供的随机源对给定列表进行混洗。
// mylist is the list to be shuffled. // rndm is source of randomness to shuffle the list. public static void shuffle(List mylist, Random rndm) It throws UnsupportedOperationException if the specified list or its list-iterator does not support the set operation.
// Java program to demonstrate working of shuffle()
// with user provided source of randomness.
import java.util.*;
public class GFG
{
public static void main(String[] args)
{
ArrayList<String> mylist = new ArrayList<String>();
mylist.add("code");
mylist.add("quiz");
mylist.add("geeksforgeeks");
mylist.add("quiz");
mylist.add("practice");
mylist.add("qa");
System.out.println("Original List : \n" + mylist);
// Here we use Random() to shuffle given list.
Collections.shuffle(mylist, new Random());
System.out.println("\nShuffled List with Random() : \n"
+ mylist);
// Here we use Random(3) to shuffle given list.
Collections.shuffle(mylist, new Random(3));
System.out.println("\nShuffled List with Random(3) : \n"
+ mylist);
// Here we use Random(3) to shuffle given list.
Collections.shuffle(mylist, new Random(5));
System.out.println("\nShuffled List with Random(5) : \n"
+ mylist);
}
}
输出:
Original List : [code, quiz, geeksforgeeks, quiz, practice, qa] Shuffled List with Random() : [qa, quiz, geeksforgeeks, code, practice, quiz] Shuffled List with Random(3) : [quiz, code, quiz, practice, qa, geeksforgeeks] Shuffled List with Random(5) : [code, practice, geeksforgeeks, qa, quiz, quiz]
重要事项:
- 此方法通过随机排列列表元素来工作
- 以线性时间运行。如果提供的列表没有实现LinkedList之类的RandomAccess接口,并且该列表很大,它将首先将列表复制到数组中,然后将数组副本混洗,最后将数组复制回列表中。这样可以确保时间保持线性。
- 它从最后一个元素到第二个元素向后遍历列表,反复将随机选择的元素交换到“current position”中。从列表中从第一个元素到当前位置(包括首尾)的部分中随机选择元素。 [来源:javadoc]
相关用法
- Java Java lang.Long.lowestOneBit()用法及代码示例
- Java Java lang.Long.numberOfTrailingZeros()用法及代码示例
- Java Java lang.Long.highestOneBit()用法及代码示例
- Java Java lang.Long.numberOfLeadingZeros()用法及代码示例
- Java Java.util.Collections.rotate()用法及代码示例
- Java Java lang.Long.reverse()用法及代码示例
- Java Java lang.Long.builtcount()用法及代码示例
注:本文由纯净天空筛选整理自 Collections.shuffle() in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。