Java 重新排列数组。做1,3,5到3,5,1等等

Java 重新排列数组。做1,3,5到3,5,1等等,java,arrays,Java,Arrays,假设我有一个数组: int array[][] = {{1, 2, 3}, {2, 5, 7}, {4, 2, 1}}; 我怎样才能做到呢 int array[][] = {{2, 5, 7}, {1, 2, 3}, {4, 2, 1}}; 或 等等 有什么JAVA函数可以帮助我吗?还是我得自己想办法 谢谢。您可以将数组转换为列表并调用Collections.shuffle()。然后转换回数组 int array[][] = {{1, 2, 3}, {2, 5, 7}, {4, 2, 1}}

假设我有一个数组:

int array[][] = {{1, 2, 3}, {2, 5, 7}, {4, 2, 1}};
我怎样才能做到呢

int array[][] = {{2, 5, 7}, {1, 2, 3}, {4, 2, 1}};

等等

有什么JAVA函数可以帮助我吗?还是我得自己想办法


谢谢。

您可以将数组转换为
列表
并调用
Collections.shuffle()
。然后转换回数组

int array[][] = {{1, 2, 3}, {2, 5, 7}, {4, 2, 1}};

List<int[]> l = Arrays.asList( array ); //the list returned is backed by the array, and thus the array is shuffled in place
Collections.shuffle( l );
//no need to convert back
int数组[][]={{1,2,3},{2,5,7},{4,2,1};
列表l=数组。asList(数组)//返回的列表由数组支持,因此数组将在适当的位置进行洗牌
收藏。洗牌(l);
//不需要重新转换
如果需要保持原始顺序,则必须创建数组(或该数组支持的列表)的副本,如下所示:

int array[][] = {{1, 2, 3}, {2, 5, 7}, {4, 2, 1}};

List<int[]> l = new ArrayList<int[]>( Arrays.asList( array ) );  //creates an independent copy of the list
Collections.shuffle( l );

int newArray[][] = l.toArray( new int[0][0] );
List<int[]> list = Arrays.asList(array);
Collections.shuffle(list);
int[][] shuffledArray = (int[][]) shuffledList.toArray();
int数组[][]={{1,2,3},{2,5,7},{4,2,1};
listl=newarraylist(Arrays.asList(array))//创建列表的独立副本
收藏。洗牌(l);
int newArray[][]=l.toArray(新int[0][0]);
另一种方式:

int array[][] = {{1, 2, 3}, {2, 5, 7}, {4, 2, 1}};

int newArray[][] = array.clone(); //copy the array direcly
List<int[]> l = Arrays.asList( newArray );
Collections.shuffle( l );
int数组[][]={{1,2,3},{2,5,7},{4,2,1};
int newArray[][]=array.clone()//直接复制数组
List l=Arrays.asList(newArray);
收藏。洗牌(l);

如果您可以使用集合,那么有一个shuffle方法,如果您必须使用诸如int之类的基元类型,那么您必须自己对其进行shuffle。以下是两者的示例:


您需要的是外部数组内容的随机交换

您可以使用java.Random的nextBoolean()来获取是否进行交换的真/假,例如1&2、1&3或2&3之间的交换


这是假设您希望使用基本类型,而不是类。

尝试Java附带的Collections类。可以使用shuffle()方法随机化索引以访问数组


使用
Collections.shuffle(..)
方法作为
数组非常简单。asList(..)
方法返回一个由
数组支持的列表

Collections.shuffle(Arrays.asList(array));

完整示例:

public static void main(String... args) {
    int array[][] = {{1, 2, 3}, {2, 5, 7}, {4, 2, 1}};
    Collections.shuffle(Arrays.asList(array));

    for (int[] a : array)
        System.out.println(Arrays.toString(a));
}
使用集合: 大概是这样的:

int array[][] = {{1, 2, 3}, {2, 5, 7}, {4, 2, 1}};

List<int[]> l = new ArrayList<int[]>( Arrays.asList( array ) );  //creates an independent copy of the list
Collections.shuffle( l );

int newArray[][] = l.toArray( new int[0][0] );
List<int[]> list = Arrays.asList(array);
Collections.shuffle(list);
int[][] shuffledArray = (int[][]) shuffledList.toArray();
List List=Arrays.asList(array);
集合。洗牌(列表);
int[][]shuffledArray=(int[][])shuffledList.toArray();

数组。asList
将为您提供一个由数组支持的列表。因此,无需运行
l.toArray(..)
。。。