无法对 Java 字符串数组进行随机化。

huangapple go评论88阅读模式
英文:

Fail to randomize java string array

问题

我想使用下面的代码对字符串数组的顺序进行随机化或洗牌

public static void main(String[] args) {
    String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
    String strTmp[]=str;

    ArrayList<Integer> list = new ArrayList<Integer>();
    for (int i=0; i<str.length; i++) {
        list.add(new Integer(i));
    }

    Collections.shuffle(list);

    for (int i=0; i<str.length; i++) {
        strTmp[i]=str[list.get(i)];
        System.out.println(strTmp[i]);
    }
}

我这样做的原因是我想稍后将其制作成一个函数。这就是为什么我将它传递给strTmp[],因为这是我想要函数返回的内容。但是,代码的实际效果与我预期的不同。它打印出了几个相同的值。请问我应该如何正确实现?谢谢解答...

英文:

I want to randomize or shuffle the order of the string array using the code below

public static void main(String[] args) {
		String str[]= {&quot;Vxds&quot;, &quot;Cvda&quot;, &quot;Xcgi&quot;, &quot;Atdr&quot;, &quot;Mbeds&quot;, &quot;0bda&quot;};
		String strTmp[]=str;
		
		ArrayList&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;();
        for (int i=0; i&lt;str.length; i++) {
            list.add(new Integer(i));
        }
        
        Collections.shuffle(list);
        
        for (int i=0; i&lt;str.length; i++) {
            strTmp[i]=str[list.get(i)];
            System.out.println(strTmp[i]);
        }
	}

The reason I do it like this instead of print it out directly is because I want to make it into a function later on. That's why I passed it to strTmp[] as that is what I want the function to return. But, the code just didn't function as I expected. It prints out several same value. How can I do it the right way? Thanks for the answer...

答案1

得分: 4

你差点就做对了,但你引用了同一个数组两次并交换了其内容。将这一行代码进行修改:

String strTmp[] = new String[str.length];
英文:

You almost had it, but you are referencing the same array twice and swap the contents of it. Change this line

 String strTmp[] = str;

to

 String strTmp[] = new String[str.length];

答案2

得分: 2

当你执行 String strTmp[]=str;strstrTmp 都是指向同一个数组的引用。因此,在放入元素时,你正在覆盖旧元素,包括那些尚未移动的元素。

你可以简单地执行以下操作:

String str[] = {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
Collections.shuffle(Arrays.asList(str));

这是有效的,因为 Arrays.asList() 不会创建新的列表,它只是在数组上提供了一个列表视图。对列表所做的任何更改都会影响数组,包括对其进行洗牌。编辑:这适用于字符串数组和任何其他引用类型的数组。正如WJS所指出的,对于原始数据类型的数组(例如 int[]),这种方法不适用,因为 Arrays.asList(arrayOfPrimitives) 会创建一个新创建的包含一个元素的原始数组的列表视图。

如果你需要一个新的数组,其中包含洗牌后的字符串,同时保持旧数组不变,解决方案如下:

List<String> list = new ArrayList<>(Arrays.asList(str));
Collections.shuffle(list);
String[] newStr = list.toArray(new String[0]);

System.out.println("Original array:     " + Arrays.toString(str));
System.out.println("New shuffled array: " + Arrays.toString(newStr));

编辑:以下是一个示例运行的输出:

Original array:     [Vxds, Cvda, Xcgi, Atdr, Mbeds, 0bda]
New shuffled array: [0bda, Cvda, Mbeds, Vxds, Xcgi, Atdr]

正如你所看到的,原始数组保持不变。

编辑:自从Java 11以后,使用 Collection.toArray(IntFunction<String[]>) 创建新数组会更加优雅:

String[] newStr = list.toArray(String[]::new);

在 IdeOne 上查看这两个代码片段的实际运行效果

英文:

When you do String strTmp[]=str;, both str and strTmp are references to the same array. So when putting elements in, you are overwriting old elements including those have not yet been moved.

You may just do

	String str[]= {&quot;Vxds&quot;, &quot;Cvda&quot;, &quot;Xcgi&quot;, &quot;Atdr&quot;, &quot;Mbeds&quot;, &quot;0bda&quot;};
    Collections.shuffle(Arrays.asList(str));

This works because Arrays.asList() does not create a new list, it merely provides a list view on the array. Any changes to the list change the array. Including shuffling it. Edit: This works for an array of strings and an array of any other reference type. As WJS points out, this will not work for an array of primitives (e.g., int[]) since Arrays.asList(arrayOfPrimitives) will create a list view of a newly created array of one elemeent, the primitive array.

If you require a new array with the shuffled strings and the old array unmodified, the solution is:

	List&lt;String&gt; list = new ArrayList&lt;&gt;(Arrays.asList(str));
    Collections.shuffle(list);
    String[] newStr = list.toArray(new String[0]);
    
    System.out.println(&quot;Original array:     &quot; + Arrays.toString(str));
    System.out.println(&quot;New shuffled array: &quot; + Arrays.toString(newStr));

Edit: Output from one example run:

> Original array: [Vxds, Cvda, Xcgi, Atdr, Mbeds, 0bda]
> New shuffled array: [0bda, Cvda, Mbeds, Vxds, Xcgi, Atdr]

As you can see, the original array is unmodified.

Edit: Since Java 11 it’s nicer to create the new array using Collection.toArray(IntFunction&lt;String[]&gt;):

    String[] newStr = list.toArray(String[]::new);

See both code snippets run live in IdeOne.

答案3

得分: 2

如果您不想更改数组 str。请尝试这个。

String str[] = {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
String strTmp[] = str.clone();
Collections.shuffle(Arrays.asList(strTmp));
System.out.println(Arrays.toString(strTmp));

输出:

[Xcgi, Cvda, Atdr, Mbeds, 0bda, Vxds]
英文:

If you don't want to change the array str. Try this.

String str[] = {&quot;Vxds&quot;, &quot;Cvda&quot;, &quot;Xcgi&quot;, &quot;Atdr&quot;, &quot;Mbeds&quot;, &quot;0bda&quot;};
String strTmp[] = str.clone();
Collections.shuffle(Arrays.asList(strTmp));
System.out.println(Arrays.toString(strTmp));

output

[Xcgi, Cvda, Atdr, Mbeds, 0bda, Vxds]

答案4

得分: 1

我理解您希望在每次执行时对数组进行随机排序。以下是实现此功能的代码。

import java.util.*;

public class Main {
    public static void main(String[] args) {
        String str[] = {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
        List<String> list = Arrays.asList(str);
        Collections.shuffle(list);
        System.out.println(list);
    }
}
英文:

I understand that you want to randomized your array in every execute. Here is the code for this.

import java.util.*;    

 public static void main(String[] args) {
        String str[]= {&quot;Vxds&quot;, &quot;Cvda&quot;, &quot;Xcgi&quot;, &quot;Atdr&quot;, &quot;Mbeds&quot;, &quot;0bda&quot;};    
        List&lt;String&gt; list =Arrays.asList(str);
        Collections.shuffle(list);
        System.out.println(list);
     }

huangapple
  • 本文由 发表于 2020年7月23日 19:15:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63052922.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定