随机化字符串数组,但没有重复元素

时间:2014-10-20 19:27:13

标签: java arrays random

我想问一下如何在Java中实现一个方法,该方法从数组中获取所有元素并对其进行随机播放。像一副扑克牌一样思考。

这是我的尝试:

// a is an array of type String
public void randomize()
{
    for(int i=0; i<k; ++i)
    {
        int idx = new Random().nextInt(k);
        String random = (a[idx]);
        System.out.println(random);
    }
}

3 个答案:

答案 0 :(得分:1)

您可以使用Collections.shuffle()。首先将数组转换为List

答案 1 :(得分:1)

使用内置方法可能是最简单,最干净的解决方案:

Collections.shuffle(Arrays.asList(a)); //shuffles the original array too

这是有效的,因为asList method(强调我的):

  

返回由指定数组支持的固定大小的列表。 ( 对返回列表的更改&#34;通过&#34;写入数组 。)

答案 2 :(得分:0)

你的意思是这样的吗?或者你正在寻找更复杂的东西?

static void shuffleArray(String[] ar)
  {
    Random rnd = new Random();
    for (int i = ar.length - 1; i > 0; i--)
    {
      int index = rnd.nextInt(i + 1);
      // Simple swap
      int a = ar[index];
      ar[index] = ar[i];
      ar[i] = a;
    }
  }