Summary of implementation methods of generating random numbers in Java _java

Source: Internet
Author: User
Tags generator static class

Random numbers are often used in actual development work. When a user is created in some systems, a random initialization password is given to the user. This password because it is random, so often only users know. After they have acquired this random password, they need to go to the system to change it immediately. This is the principle of using random numbers. In short, random numbers are often used in daily development work. and different development languages produce random numbers of methods and techniques are different. The author takes the Java language as an example to discuss the method of random number generation and some techniques.

first, using the random method to generate random numbers.
Generating random numbers in the Java language is relatively straightforward, because there is a ready-made way to use them. In the math class, the Java language provides a method called random. This method allows the system to produce random numbers. By default, however, it produces a smaller range of random numbers, a double random number greater than or equal to 0 to less than 1. Although its random number produced a smaller range, can not meet the day-to-day needs. As in daily work, you may need to generate random numbers of integers. In fact, as long as some flexible processing of this method, you can get arbitrary range of random numbers.
If we can first generate a random number through the random method, then multiply the result by 10. The random number produced at this point is a number greater than or equal to 0 less than 10. The int method is then used to convert it (it removes the number of decimal digits, that is, only the integer part, not rounding). Finally, we can get an integer random number from 0 to 9. Its implementation is very simple, that is, the original Random method according to the following format variant: (int) (Math.random () *10) can be. In fact, we can also extend this method to produce random numbers in any range. To replace this 10 with N, change to (int) (Math.random () *n). At this point, the application produces a random number that is greater than or equal to 0 small and N. If you set N to 5, it produces a random number of integers between 0 and 5. If you write this as a method with parameters, then as long as the user input needs to generate the maximum number of random numbers, you can let this method to generate a range of random numbers. Define your own tool library in Java
Sometimes a programmer might need to generate a random even number or odd number within a specified range. Can this be achieved by this method at this time? The answer is yes. As now, the program needs to generate an even number within a 1-100 range. How do you do this at this point? First, you need to generate a random number from 0 to 99 (as for why 99 is here, you'll see why). To implement this requirement, it is easy to do so as long as the following statement can be implemented: i=1+ (int) (Math.random () *100). where (int) (Math.random () *99) produces an integer random number from 0 to 99. Then plus 1 is a random integer that produces between 1 and 100. The resulting random number is then assigned to the variable i. But at this point the random number produced is even and odd. What the programmer needs now is a random even number. Then we can add an if judgment statement at the back. Dividing this random number by 2, if there is no remainder (or the remainder is 0), it means that the random number is even and can be returned directly. If it returns the remainder is not zero, then it is an odd number, we only add 1 to become an even, return. Note that in the above random number generation, the author uses a range of 0 to 99, and then add 1 to make it 1 to 100 of the random number. The final result is to generate a random even number between 100 and 1. In fact, if you want to range randomly odd, you need to make a slight change to the above statement. Java: Changing the world between you and me
Suppose now that the user wants to generate an odd or even number within any range, can it be implemented? Suppose that the user now wants to implement an arbitrary even number between M and N (where m
It can be seen that although the random method has a strict range limit for its own random number. However, as long as the reasonable conversion, the programmer can still use this method to generate the random data users need.

Second, generating random numbers by random classes.
In the Java language, in addition to generating random numbers through the random method, a random class can be used to produce random numbers. The program developer can create a random number generator by instantiating a random object. such as Random i=new Random (). This statement uses the random class to create a random number generator. However, when creating random numbers in this way, it is different from the mechanism of using random method to produce random numbers. When instantiating an object in this way, the Java compiler takes the current time of the system as the seed of the random number generator. Because time is always changing. If we take this time as the seed of the generator, we can guarantee that the random number generated is really random, and the repetition rate of random number generated will be greatly reduced. The
is easier to use with this method. If you can take advantage of the provided keyword, let the program return a random integer (with int nextint (10)) and so on. However, it is more difficult to return control than the random method. If the system now needs to provide a random odd number between 10 and 50, this random class cannot be completed. In other words, using this random class to generate random numbers, it can only control the upper limit, but not the lower limit. In other words, it can specify the maximum range of random numbers, not the smallest random number range. So, in flexibility, it's a little bit more than the random method. The
also uses this method to implement, you must first create an object. This means using the Randow class to create the object. This is different from the Randow method. As in the example above, the Randow method itself is a method in the math class that can be invoked directly to omit the method created by the object. To this end, I suggest readers and program developers, it is best to use the random method to create random numbers. The random class is used only when generating some of the more specific random numbers. If we need to generate a double value random number with a probability density of Gaussian distribution, it is comparatively simpler to create a random number by using the random class method.

Third, the generation of random characters.
the two methods described above produce random numerical data. But sometimes the user may also need to produce random characters. In fact, the random method can be used to generate random characters. If you can use code to generate a random lowercase character: (char) (' A ' +math.random () * (' Z '-' a ' + 1)). In fact, this is similar to generating random numbers of any two numbers. By using the above code, you can generate arbitrary random characters within a range. By properly trimming this code, you can also generate random characters between arbitrary two characters and arbitrary uppercase characters. The way it is converted is similar to the random number in any range mentioned above. If you are interested, you can test it yourself. The Master leads the door and practises himself. If the author here peremptorily all the answers to everyone, everyone's impression will not be very deep. If you go back and try yourself, it's easier to remember.
I'm here to give you a hint, simply adjust the code (char) (' A ' +math.random () * (' Z '-' a ' + 1) ') according to the m+ (int) (Math.random () * (N-M)).

Fourth, advanced
by reading the source code of Math.random () or simply using the IDE's AutoComplete feature, developers can easily find that java.lang.Math.random () uses an internal randomly generated object- A very powerful object can be randomly generated: Boolean, all numeric types, even Gaussian distributions. For example:

New Java.util.Random (). Nextint (10)

It has a drawback, is that it is an object. Its method must be invoked through an instance, which means that its constructor must be called first. An expression like the above is acceptable if there is sufficient memory, but it can cause problems when there is not enough memory.

A simple solution that avoids creating a new instance each time a random number needs to be generated, and that is using a static class. Guess you may have thought of Java.lang.Math, well, we are the initialization of improved java.lang.Math. Although the project is low, you need to do some simple unit tests to make sure it doesn't go wrong.

If the program needs to generate a random number to store, the problem comes again. For example, it is sometimes necessary to manipulate or protect seed (seed), an internal number to store the state and compute the next random number. In these special cases, it is not appropriate to share randomly generated objects.

In the context of Java EE multi-threaded applications, randomly generated instance objects can still be stored in classes or other implementation classes as a static property. Fortunately, Java.util.Random is thread-safe, so there is no risk that multiple thread invocations can damage seed (seed).

Another example of multithreading java.lang.ThreadLocal is the one that is worth considering. The lazy approach is to implement a single instance through the Java API itself, and of course you can ensure that each thread has its own instance object.

Although Java does not provide a good way to manage a single instance of Java.util.Random. However, the long-awaited Java 7 provides a new way to generate random numbers:

Java.util.concurrent.ThreadLocalRandom.current (). Nextint (10)

This new API combines the benefits of two other approaches: single instance/static access, just as flexible as math.random (). Threadlocalrandom is also faster than any other method that handles high concurrency.

Chris marasti-georg points out:

Math.Round (Math.random () * 10)

Make the distribution unbalanced, for example: 0.0-0.499999 will be rounded to 0, while 0.5 to 1.499999 will be rounded to 1. So how do you use legacy syntax to achieve the right equilibrium distribution, as follows:

Math.floor (Math.random () * 11)

Luckily, if we use Java.util.Random or java.util.concurrent.ThreadLocalRandom, we don't have to worry about the problem.

The Java Combat Project introduces some of the hazards of improper use of the Java.util.Random API. This lesson tells us not to use:

Math.Abs (Rnd.nextint ())%n

and use:

Rnd.nextint (N)

Related Article

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: 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.