Java 结合赋值/组合运算符的随机值

Java 结合赋值/组合运算符的随机值,java,random,assignment-operator,Java,Random,Assignment Operator,下面的代码示例是创建两个随机值,还是重复使用第一个 Random r = new Random(); int[] a = new int[10]; a[r.nextInt(10)] += 1; // Equals this, creating two random values: a[r.nextInt(10)] = a[r.nextInt(10)] + 1; // Or this, using 6 as the result of the first random operation a

下面的代码示例是创建两个随机值,还是重复使用第一个

Random r = new Random();
int[] a = new int[10];

a[r.nextInt(10)] += 1;

// Equals this, creating two random values:
a[r.nextInt(10)] = a[r.nextInt(10)] + 1;

// Or this, using 6 as the result of the first random operation
a[6] = 6 + 1;

编辑:当我们进行编辑时,这个操作符(以及其他像
-=
/=
等)有名字吗?

当你写
a[r.nextInt(10)]+=1只生成一个随机数。因此,如果这个随机数恰好是
6
,这相当于
a[6]=a[6]+1(但效率略高)

这个操作符(和其他像-=,/=,等等)有名字吗


他们被称为快捷分配操作符。

虽然我没有否决投票,但理解什么是
+=
就足以回答这个问题,这在JLS中。测试很容易,尽管您需要迭代以确保您超过了重复随机值的概率。您不需要重复很长时间。