The first season of Java HashSet Small case: Get 10 random numbers from 1 to 20, requiring random numbers to not be duplicated

Source: Internet
Author: User
Tags set set

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.