前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >java在数组中放入随机数_如何在Java中随机播放数组

java在数组中放入随机数_如何在Java中随机播放数组

作者头像
用户7886150
修改于 2020-12-14 06:08:25
修改于 2020-12-14 06:08:25
1.5K0
举报
文章被收录于专栏:bit哲学院bit哲学院

参考链接: Java中的数组Array

java在数组中放入随机数

 There are two ways to shuffle an array in Java.

  有两种方法可以在Java中随机播放数组。  

 Collections.shuffle() Method Collections.shuffle()方法 Random Class 随机类 

  1.使用Collections类对数组元素进行混洗 (1. Shuffle Array Elements using Collections Class) 

 We can create a list from the array and then use the Collections class shuffle() method to shuffle its elements. Then convert the list to the original array.

  我们可以从数组创建一个列表,然后使用Collections类的shuffle()方法来对其元素进行随机排序。 然后将列表转换为原始数组。  

 package com.journaldev.examples;

import java.util.Arrays;

import java.util.Collections;

import java.util.List;

public class ShuffleArray {

    public static void main(String[] args) {

        Integer[] intArray = { 1, 2, 3, 4, 5, 6, 7 };

        List<Integer> intList = Arrays.asList(intArray);

        Collections.shuffle(intList);

        intList.toArray(intArray);

        System.out.println(Arrays.toString(intArray));

    }

}

 Output: [1, 7, 5, 2, 3, 6, 4]

  输出: [1、7、5、2、3、6、4]  

 Note that the Arrays.asList() works with an array of objects only. The concept of autoboxing doesn’t work with generics. So you can’t use this way to shuffle an array for primitives.

  请注意,Arrays.asList()仅适用于对象数组。 自动装箱的概念不适用于泛型 。 因此,您不能使用这种方法来为基元改组数组。  

  2.使用随机类随机排列数组 (2. Shuffle Array using Random Class) 

 We can iterate through the array elements in a for loop. Then, we use the Random class to generate a random index number. Then swap the current index element with the randomly generated index element. At the end of the for loop, we will have a randomly shuffled array.

  我们可以在for循环中遍历数组元素。 然后,我们使用Random类来生成随机索引号。 然后将当前索引元素与随机生成的索引元素交换。 在for循环的末尾,我们将有一个随机混排的数组。  

 package com.journaldev.examples;

import java.util.Arrays;

import java.util.Random;

public class ShuffleArray {

    public static void main(String[] args) {

        int[] array = { 1, 2, 3, 4, 5, 6, 7 };

        Random rand = new Random();

        for (int i = 0; i < array.length; i++) {

            int randomIndexToSwap = rand.nextInt(array.length);

            int temp = array[randomIndexToSwap];

            array[randomIndexToSwap] = array[i];

            array[i] = temp;

        }

        System.out.println(Arrays.toString(array));

    }

}

 Output: [2, 4, 5, 1, 7, 3, 6]

  输出: [2、4、5、1、7、3、6]  

  翻译自: https://www.journaldev.com/32661/shuffle-array-java

 java在数组中放入随机数

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档