Recently, we need to develop a random advertisement function. In the previous blog, we talked about the Oracle method.
In this article, we will share how to randomly fetch numbers in the Java list:
In fact, there is no method to randomly retrieve records in the list, but there is a shuffle method in collections to achieve the "shuffling" effect. The so-called "shuffling" means to disrupt the elements in the list and re-sort them. The list after the list is rearranged and the number of records to be sent from the first place is equivalent to the random number acquisition. For details, see the code.
Import Java. util. arraylist; <br/> Import Java. util. collections; <br/> Import Java. util. list; <br/> public class TTL {<br/> Public static void main (string [] Str) {<br/> List <integer> List = new arraylist <integer> (); <br/> for (INT I = 0; I <5; I ++) {<br/> list. add (I); <br/>}< br/> system. out. println ("orginal list:"); <br/> for (integer S: List) {<br/> system. out. print (s); <br/>}< br/> system. out. println (); </P> <p> collections. shuffle (list); <br/> system. out. println ("after shuffle list:"); <br/> for (integer S: List) {<br/> system. out. print (s); <br/>}< br/>
Output result:
Orginal list:
01234
After shuffle list:
32041
The shuffle principle is to use the SWAp in the collection to implement random transposition of each element in the list. This means that this random method is not suitable for the random of many records in the list.