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

java在数组中放入随机数

There are two ways to shuffle an array in Java.

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

  1. Collections.shuffle() Method

    Collections.shuffle()方法
  2. 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在数组中放入随机数

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值