This is based on the uniqueness of the HashSet collection.
/*
* Write a program that gets 10 random numbers from 1 to 20, requiring random numbers to not be duplicated.
*
Analysis
* A: Create random number objects
* B: Create a HashSet collection
* C: Determine if the length of the set is less than 10
* Yes: Create a random number to add
* No: Ignore it
* D: Traverse HashSet Collection
*/
The code writes out:
Import Java.util.hashset;import Java.util.random;public class Hashsetdemo {public static void main (string[] args) {//Create with Machine Number Object Random r = new Random ();//Create a set set hashset<integer> ts = new hashset<integer> ();// The integer has rewritten the hashcode and Equals methods,//So the automatic judgment is the same, and excludes the same elements, guaranteeing the uniqueness of the element//Judging whether the length of the set is less than 10. A total of 10 numbers while (Ts.size () <) {int num = r.nextint () +1;ts.add (num),//hashset guarantees element uniqueness, and duplicate values are not stored at all. The reason is that the integer has overridden the hashcode and equals methods,}//iterates the set set for (Integer i:ts) {System.out.println (i);}}}
Results:
19
4
20
7
8
10
11
13
14
15
No duplication occurs.
The first season of Java HashSet Small case: Get 10 random numbers from 1 to 20, requiring random numbers to not be duplicated