package tryAny.effectiveJava;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.commons.lang3.time.StopWatch;
public class RandomTest {
public static void main(String[] args) {
int n = 2 * (Integer.MAX_VALUE / 3);
int low1 = 0;
StopWatch sw1 = new StopWatch();
sw1.start();
for (int i = 0; i < 1000000; i++) {
if (random(n) < n / 2) {
low1++;
}
}
sw1.stop();
System.out.println(low1); //I don't think it will be around 500,000. 666 666th place.
System.out.println(sw1.getTime());
int low2 = 0;
StopWatch sw2 = new StopWatch();
sw2.start();
for (int i = 0; i < 1000000; i++) {
if (tlr.nextInt(n) < n / 2) {
low2++;
}
}
sw2.stop();
System.out.println(low2);//It will be around 500,000.
System.out.println(sw2.getTime());//The speed does not change much
}
static Random rnd = new Random();
static int random(int n) {
return Math.abs(rnd.nextInt()) % n;
}
static ThreadLocalRandom tlr = ThreadLocalRandom.current();
}
There are five advantages that can be obtained by using the library instead of writing the process yourself.
You can use the implementation that the expert has elaborated.
Save time.
As the library itself evolves, you will benefit from it.
The functionality of the library will increase with each release, so you can benefit from it.
By using a standard library, your code will be mainstream, easy to read and use.
All programmers should be familiar with java.lang, java.util, java.io and their subpackages.
Recommended Posts