[Java] Common tool classes of Java core classes

Common Tools

Java's core library provides a large number of ready-made classes for us to use. In this section we introduce several commonly used tool classes.

Math

As the name implies, Maththe class is used for mathematical calculations, and it provides a large number of static methods to facilitate our implementation of mathematical calculations:

Find the absolute value:

Math.abs(-100); // 100
Math.abs(-7.8); // 7.8

Take the largest or smallest value:

Math.max(100, 99); // 100
Math.min(1.2, 2.3); // 1.2

Calculate the xy power:

Math.pow(2, 10); // 2的10次方=1024

Calculate √x:

Math.sqrt(2); // 1.414...

Calculate the ex power:

Math.exp(2); // 7.389...

Calculate the logarithm to base e:

Math.log(4); // 1.386...

Calculate base 10 logarithms:

Math.log10(100); // 2

Trigonometric functions:

Math.sin(3.14); // 0.00159...
Math.cos(3.14); // -0.9999...
Math.tan(3.14); // -0.0015...
Math.asin(1.0); // 1.57079...
Math.acos(1.0); // 0.0

Math also provides several mathematical constants:

double pi = Math.PI; // 3.14159...
double e = Math.E; // 2.7182818...
Math.sin(Math.PI / 6); // sin(π/6) = 0.5

Generate a random number x, the range of x is 0 <= x < 1:

Math.random(); // 0.53907... 每次都不一样

If we want to generate a [MIN, MAX)random number in the interval, we can use Math.random()the implementation, the calculation is as follows:

 
 

Some children's shoes may have noticed that the Java standard library also provides a method StrictMaththat provides Mathalmost exactly the same method as . The difference between these two classes is that due to errors in floating-point calculations, the calculation results of different platforms (such as x86 and ARM) may be inconsistent (referring to different errors). Therefore, it is guaranteed that the calculation results of all platforms are exactly the same, but StrictMathwill Mathbe Try to optimize the computing speed for the platform, so in most cases, using it Mathis enough.

HexFormat

When dealing with byte[]arrays, we often need to convert to and from hexadecimal strings, which is cumbersome to write by ourselves, but the ones provided by the Java standard library HexFormatcan easily help us convert.

To byte[]convert an array to a hexadecimal string, you can use formatHex()the method:

import java.util.HexFormat;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        byte[] data = "Hello".getBytes();
        HexFormat hf = HexFormat.of();
        String hexData = hf.formatHex(data); // 48656c6c6f
    }
}

If you want to customize the conversion format, use the customized HexFormatinstance:

// 分隔符为空格,添加前缀0x,大写字母:
HexFormat hf = HexFormat.ofDelimiter(" ").withPrefix("0x").withUpperCase();
hf.formatHex("Hello".getBytes())); // 0x48 0x65 0x6C 0x6C 0x6F

To convert from a hexadecimal string to byte[]an array, use parseHex():

byte[] bs = HexFormat.of().parseHex("48656c6c6f");

random

RandomUsed to create pseudo-random numbers. The so-called pseudo-random number means that as long as an initial seed is given, the sequence of random numbers generated is exactly the same.

To generate a random number, use nextInt(), nextLong(), nextFloat(), nextDouble():

Random r = new Random();
r.nextInt(); // 2071575453,每次都不一样
r.nextInt(10); // 5,生成一个[0,10)之间的int
r.nextLong(); // 8811649292570369305,每次都不一样
r.nextFloat(); // 0.54335...生成一个[0,1)之间的float
r.nextDouble(); // 0.3716...生成一个[0,1)之间的double

Some children's shoes asked, every time the program is run, the generated random numbers are different, and the characteristics of pseudo-random numbers are not seen .

This is because when we create Randoman instance, if we do not give a seed, we will use the current timestamp of the system as the seed, so each time we run, the seed is different, and the sequence of pseudo-random numbers obtained is different.

If we Randomspecify a seed when creating an instance, we get a completely deterministic sequence of random numbers:

import java.util.Random;

 Run

The one we used earlier Math.random()actually calls Randomthe class internally, so it is also a pseudo-random number, but we cannot specify the seed.

SecureRandom

Where there are pseudo-random numbers, there are true random numbers. In fact, the real true random number can only be obtained through the principle of quantum mechanics, and what we want is an unpredictable and safe random number, which is SecureRandomused to create a safe random number:

SecureRandom sr = new SecureRandom();
System.out.println(sr.nextInt(100));

SecureRandomThere is no way to specify a seed, it uses the RNG (random number generator) algorithm. JDK SecureRandomactually has a variety of different underlying implementations, some use secure random seeds plus pseudo-random number algorithms to generate secure random numbers, and some use real random number generators. In actual use, you can first obtain a high-strength secure random number generator. If not provided, use a normal-level secure random number generator:

import java.util.Arrays;
import java.security.SecureRandom;
import java.security.NoSuchAlgorithmException;

SecureRandomThe security of is to generate random numbers through a secure random seed provided by the operating system. This seed is the "entropy" generated by various random events such as thermal noise of the CPU, bytes read and written to disk, network traffic, etc.

In cryptography, secure random numbers are very important. If unsafe pseudo-random numbers are used, all encryption systems will be broken. Therefore, always keep in mind that you must use SecureRandomto generate secure random numbers.

 When you need to use secure random numbers, you must use SecureRandom, never use Random!

summary

The common tool classes provided by Java are:

  • Math: mathematical calculations

  • Random: generate pseudo-random numbers

  • SecureRandom: Generate secure random numbers

Guess you like

Origin blog.csdn.net/ihero/article/details/131906668