Java,List生成二维数组

利用list.toArray(T[] a)方法

例如:

List<double[]>转double[][]

List<double[]>list=new ArrayList<double[]>();
list.add(new double[]{10.0,12.0});
list.add(new double[]{11.0,32.0});
double[][]result=list.toArray(new double[0][0]);

附上JDK的文档:

<T> T[] toArray(T[] a)返回按适当顺序(从第一个元素到最后一个元素)包含列表中所有元素的数组;返回数组的运行时类型是指定数组的运行时类型。如果指定数组能容纳列表,则在其中返回该列表。否则,分配具有指定数组的运行时类型和此列表大小的新数组。
如果指定数组能容纳列表,并剩余空间(即数组的元素比列表的多),那么会将数组中紧随列表尾部的元素设置为 null。(只有在调用者知道列表不包含任何 null 元素时此方法才能用于确定列表的长度)。

像 toArray() 方法一样,此方法充当基于数组的 API 与基于 collection 的 API 之间的桥梁。更进一步说,此方法允许对输出数组的运行时类型进行精确控制,在某些情况下,可以用来节省分配开销。

假定 x 是只包含字符串的一个已知列表。以下代码用来将该列表转储到一个新分配的 String 数组:

     String[] y = x.toArray(new String[0]);注意,toArray(new Object[0]) 和 toArray() 在功能上是相同的。

指定者:
接口 Collection<E> 中的 toArray
参数:
a - 要存储列表中元素的数组,如果它足够大的话;否则为此目的分配一个运行时类型相同的新数组。
返回:
包含列表中元素的数组
抛出:
ArrayStoreException - 如果指定数组的运行时类型不是此列表中每个元素的运行时类型的超类型
NullPointerException - 如果指定数组为 null

 

好的,我可以帮你写一个Java函数来实现这个需求。这里我使用了Prim算法生成随机迷宫。 ```java public static int[][] generateMaze(int width, int height) { int[][] maze = new int[height][width]; Random random = new Random(); // 初始化迷宫,全部设置为墙 for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { maze[i][j] = 1; } } // 随机选择起点和终点 int startX = random.nextInt(width); int startY = random.nextInt(height); int endX = random.nextInt(width); int endY = random.nextInt(height); // 设置起点和终点 maze[startY][startX] = 2; maze[endY][endX] = 2; // 使用Prim算法生成迷宫 List<int[]> walls = new ArrayList<>(); walls.add(new int[]{startX, startY, startX, startY}); while (!walls.isEmpty()) { int index = random.nextInt(walls.size()); int[] wall = walls.remove(index); int x1 = wall[0]; int y1 = wall[1]; int x2 = wall[2]; int y2 = wall[3]; int nx = x2 + (x1 - x2) / 2; int ny = y2 + (y1 - y2) / 2; if (maze[ny][nx] == 1) { maze[ny][nx] = 0; maze[y1][x1] = 0; maze[y2][x2] = 0; if (nx > 1) { walls.add(new int[]{nx, ny, nx - 1, ny}); } if (ny > 1) { walls.add(new int[]{nx, ny, nx, ny - 1}); } if (nx < width - 2) { walls.add(new int[]{nx, ny, nx + 1, ny}); } if (ny < height - 2) { walls.add(new int[]{nx, ny, nx, ny + 1}); } } } return maze; } ``` 这个函数接收两个参数:迷宫的宽度和高度。它首先创建一个全部设置为墙的二维数组,然后随机选择起点和终点,并将它们标记为 2。接着,它使用 Prim 算法生成迷宫,并将迷宫中的空地设置为 0。最后,它返回这个二维数组。 你可以像这样调用这个函数: ```java int[][] maze = generateMaze(10, 10); for (int i = 0; i < maze.length; i++) { for (int j = 0; j < maze[i].length; j++) { System.out.print(maze[i][j] + " "); } System.out.println(); } ``` 这将生成一个宽度和高度均为 10 的迷宫,并将其打印到控制台上。输出的结果可能是这样的: ``` 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 0 1 0 0 1 1 0 0 1 1 0 0 1 0 1 1 0 0 0 1 0 1 0 0 1 1 0 0 1 0 0 0 1 0 1 1 0 1 0 0 1 0 0 0 1 1 0 1 0 1 0 0 1 0 1 1 0 1 0 0 0 0 0 0 1 1 0 1 1 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 ``` 其中 1 表示墙,2 表示起点和终点,0 表示空地。左上角是起点,右下角是终点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值