Java 常用自带类
2020.03.01 17:49
2020.03.01 17:50
1. Java常用类
1.1. Math
Java的Math类封装了很多与数学有关的属性和方法。
- Math.sqrt()//计算平方根
- Math.cbrt()//计算立方根
- Math.hypot(x,y)//计算 (x的平方+y的平方)的平方根
public static void main(String[] args) {
/* Math.sqrt()//计算平方根
* Math.cbrt()//计算立方根
* Math.hypot(x,y)//计算 (x的平方+y的平方)的平方根
*/
System.out.println(Math.sqrt(16));//4.0
System.out.println(Math.cbrt(8));//2.0
System.out.println(Math.hypot(3, 4));//5.0
}
- Math.pow(a,b)//计算a的b次方
- Math.exp(x)//计算e^x的值
System.out.println(Math.pow(3, 2));//9.0
System.out.println(Math.exp(3));//20.085536923187668
- Math.max();//计算最大值
- Math.min();//计算最小值
System.out.println(Math.max(1, 2));//2
System.out.println(Math.min(3, 1));//1
- Math.abs求绝对值
System.out.println(Math.abs(-12.3));//12.3
System.out.println(Math.abs(12));//12
- Math.ceil()向上取整
- Math.floor()向下取整
System.out.println(Math.ceil(12.3));//13.0
System.out.println(Math.floor(-11.1));//-12.0
- Math.random()取随机数
System.out.println(Math.random());//0.23394287790939905
- Math.round()取随机数
System.out.println(Math.round(4.4));//4
System.out.println(Math.round(4.5));//5
1.2. Random
Random
用来创建伪随机数。所谓伪随机数,是指只要给定一个初始的种子,产生的随机数序列是完全一样的。
要生成一个随机数,可以使用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
1.3. SecureRandom
有伪随机数,就有真随机数。实际上真正的真随机数只能通过量子力学原理来获取,而我们想要的是一个不可预测的安全的随机数,SecureRandom
就是用来创建安全的随机数的:
SecureRandom sr = new SecureRandom();
System.out.println(sr.nextInt(100));
SecureRandom
无法指定种子,它使用RNG(random number generator)算法。
JDK的SecureRandom
实际上有多种不同的底层实现,有的使用安全随机种子加上伪随机数算法来产生安全的随机数,有的使用真正的随机数生成器。实际使用的时候,可以优先获取高强度的安全随机数生成器,如果没有提供,再使用普通等级的安全随机数生成器:
public static void main(String[] args) {
SecureRandom sr = null;
try {
sr = SecureRandom.getInstanceStrong(); // 获取高强度安全随机数生成器
} catch (NoSuchAlgorithmException e) {
sr = new SecureRandom(); // 获取普通的安全随机数生成器
}
byte[] buffer = new byte[16];
sr.nextBytes(buffer); // 用安全随机数填充buffer
System.out.println(Arrays.toString(buffer));
}
SecureRandom
的安全性是通过操作系统提供的安全的随机种子来生成随机数。这个种子是通过CPU的热噪声、读写磁盘的字节、网络流量等各种随机事件产生的“熵”。
本节阅读完毕!
(分享)