用java实现一个遍历一个数组A,将遍历出来的数据再装到另一个数组B中,但是数组B只能存三个数组,当B数组满三个后就自动创建新的数组C再往数组C里添加三个数组,让前一个数组满了后会创建另一个数组接着存储,最后将遍历出来存储的数组全部都存储在一个集合里面
时间: 2023-10-07 21:14:18 浏览: 55
可以使用Java中的ArrayList来实现这个功能。以下是一个示例代码:
```java
import java.util.ArrayList;
public class ArrayTraversal {
public static void main(String[] args) {
int[] arrayA = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // 假设有一个数组A
ArrayList<int[]> collection = new ArrayList<>(); // 创建一个集合存储数组
int[] currentArray = new int[3]; // 创建当前数组
int currentIndex = 0; // 当前数组的索引
for (int i = 0; i < arrayA.length; i++) {
currentArray[currentIndex] = arrayA[i]; // 将遍历出来的数据存入当前数组
currentIndex++; // 当前数组索引加一
if (currentIndex == 3) { // 当当前数组满三个元素时
collection.add(currentArray); // 将当前数组存入集合
currentArray = new int[3]; // 创建新的数组
currentIndex = 0; // 重置当前数组的索引
}
}
// 处理最后一个数组(可能不满三个元素)
if (currentIndex > 0) {
int[] lastArray = new int[currentIndex];
System.arraycopy(currentArray, 0, lastArray, 0, currentIndex);
collection.add(lastArray);
}
// 打印集合中的数组
for (int[] array : collection) {
System.out.print("[");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
if (i != array.length - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
}
}
```
这个示例代码中,首先创建了一个数组A,然后使用ArrayList来存储数组。遍历数组A,将数据存入当前数组currentArray,并在满足条件时将当前数组存入集合collection。最后,打印出集合中的所有数组。请注意,最后一个数组可能不满三个元素,需要特别处理一下。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)