如何使用java按升序生成包含随机数的数组

如何使用java按升序生成包含随机数的数组,java,arrays,Java,Arrays,我想让数组按升序包含随机数,例如(1,5,10…100),而不是(5,1,10…)。 此代码但运行时数字不能递增。什么错误 Random r=new Random(); int t=10; int a[]=new int[t]; int count=0; int end=0; int curr=0; while(count<t){ curr=r.nextInt(); end=end+curr;

我想让数组按升序包含随机数,例如(1,5,10…100),而不是(5,1,10…)。 此代码但运行时数字不能递增。什么错误

     Random r=new Random();
     int t=10;
       int a[]=new int[t];
     int count=0;
     int end=0;
     int curr=0;
     while(count<t){
     curr=r.nextInt();
     end=end+curr;
     count++;}
     for(int i=0;i<to;i++){
     a[i]=r.nextInt(10);}
 ```
Random r=new Random();
int t=10;
int a[]=新的int[t];
整数计数=0;
int end=0;
int curr=0;

while(count您可以使用
Random#int
方法返回随机int值流。假设您希望从范围
[1100]中选择10个随机int
按升序排序:

Random r = new Random();
int t    = 10;
int a[]  = r.ints(1, 100).distinct().limit(t).sorted().toArray();
System.out.println(Arrays.toString(a));
如果要允许重复,可以省略
distinct

要按降序排序,您需要将primitiv类型装箱为整数,并使用
Comparator.reverseOrder()
Collections.reverseOrder()
并在排序后取消装箱以将其存储在int数组中

int a[]  = r.ints(0, 100)
                .distinct()
                .limit(t)
                .boxed()
                .sorted(Comparator.reverseOrder())
                .mapToInt(Integer::intValue)
                .toArray();

可能是这样的?如果您保存以前生成的值以用于生成下一个值,唯一的缺点是,当生成的随机值非常高时,如链接中所示…@Maymunah Edited。非常感谢。