Java小白踩坑录 - Random 揭秘(二)

简介: Java小白踩坑录 - Random 揭秘(二)

假设 a=Integer.MIN_VALUE 即 -2147483648(0x80000000),假设返回 int 的值 2147483648 会发生溢出,因为 int 的最大值为 2147483647(0x7fffffff),溢出后又变成了 0x80000000,即 Integer.MIN_VALUE


源码详细描述如下:



/**
 * Returns the absolute value of an {@code int} value.
 * If the argument is not negative, the argument is returned.
 * If the argument is negative, the negation of the argument is returned.
 *
 * <p>Note that if the argument is equal to the value of
 * {@link Integer#MIN_VALUE}, the most negative representable
 * {@code int} value, the result is that same value, which is
 * negative.
 *
 * @param a the argument whose absolute value is to be determined
 * @return the absolute value of the argument.
 */
 public static int abs(int a) {
  return (a < 0) ? -a : a;
 }

Java 类库提供了一个带 seed 的方法来解决上面的问题,就是 Random.nextInt(n)。


总结


随机数的生成器涉及了很多算法的相关知识,幸运的是,我们并不需要自己来做这些工作,我们可以利用现成的成果为我们所用,如 Random.nextInt(n) 或者 java.security.SecureRandom,或者第三方的 API。注意:我们尽量使用类库,而不是自己去开发。


Linux 系统有 /dev/random,/dev/urandom 向用户提供真随机数。


目录
相关文章
|
Java
java的Random类和Arrays.sort类使用实例
java的Random类和Arrays.sort类使用实例
83 1
|
Java
java值random类的使用
java值random类的使用
90 0
|
Java
java的Math类和random类
java的Math类和random类
83 0
Java系类 之 生成随机数(random()和Random类)
这篇文章介绍了Java中生成随机数的两种方法:使用`Math.random()`方法和`Random`类的实例方法,并提供了示例代码展示如何使用这些方法生成特定范围或特定条件下的随机数。
|
算法 Java 测试技术
滚雪球学Java(55):想让你的程序更有趣?加上这个Java的Random类的小技巧!
【6月更文挑战第9天】🏆本文收录于「滚雪球学Java」专栏,专业攻坚指数级提升,希望能够助你一臂之力,帮你早日登顶实现财富自由🚀;同时,欢迎大家关注&&收藏&&订阅!持续更新中,up!up!up!!
150 2
滚雪球学Java(55):想让你的程序更有趣?加上这个Java的Random类的小技巧!
|
Java C语言
JAVA 初识 (一)JOptionPane、Scanner和Random的小认知
JAVA 初识 (一)JOptionPane、Scanner和Random的小认知
|
Java
Java——Math、BigInteger和Random类
Java——Math、BigInteger和Random类
101 0
|
存储 Java
35、Java 中的 Math 类、Random 随机数、UUID、格式化字符串或数字、字符串和数字的相互转换、高精度计算、BigDecimal、计算机中的浮点数都是近似值
35、Java 中的 Math 类、Random 随机数、UUID、格式化字符串或数字、字符串和数字的相互转换、高精度计算、BigDecimal、计算机中的浮点数都是近似值
263 0
|
安全 Java 数据安全/隐私保护
java random随机数的用法
java random随机数的用法
【零基础学Java】—Random的基本概述和使用(十二)
【零基础学Java】—Random的基本概述和使用(十二)