4

Is it possible to choose a random element from one array and move it to another without the aid of ArrayLists/Collections etc (unless you can use shuffle on an array)? and making sure that element isn't selected again? I thought about setting it to null seems you cannot remove it but I'm unsure.

Basically i want myArray to get shuffled or randomized and I figured the best way would be to pull them from one in a random order and add them to a new one...

Roman C
  • 49,761
  • 33
  • 66
  • 176
binary101
  • 1,013
  • 3
  • 23
  • 34

3 Answers3

6

You can use Collections.shuffle(List) to shuffle an array as well:

Integer[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Collections.shuffle(Arrays.asList(data));

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

will print e.g. [6, 2, 4, 5, 10, 3, 1, 8, 9, 7].

Arrays.asList will not create a new list, but a List interface wrapper for the array, so that changes to the list are propagated to the array as well.

jarnbjo
  • 33,923
  • 7
  • 70
  • 94
3

You can use Collections.shuffle() method to shuffle a list.

Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
Ashwinee K Jha
  • 9,187
  • 2
  • 25
  • 19
2

- You can use a Collection like List and then use shuffle() method.

- Or if you want to stick with the Array then first you need to convert the array into List and then use shuffle() method.

Eg:

Integer[] arr = new Integer[10];

List<Integer> i = new ArrayList<Integer>(Arrays.asList());

Collections.shuffle(i);
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75