假设以下是我们的数组-
Integer[] arr = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
现在,我们可以在将其改组之前将其转换为列表-
List<Integer>list = Arrays.asList(arr); Collections.shuffle(list);
上述改组生成随机元素。这样显示它们-
for (Integer res: list) { System.out.print(res + " "); }
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Demo { public static void main(String[] args) { Integer[] arr = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; System.out.print("Array elements...\n"); for (Integer res: arr) { System.out.print(res + " "); } List<Integer>list = Arrays.asList(arr); Collections.shuffle(list); System.out.println("\n\nRandom elements..."); for (Integer res: list) { System.out.print(res + " "); } } }
输出结果
Array elements... 2 4 6 8 10 12 14 16 18 20 Random elements... 18 16 4 20 12 14 10 2 6 8