java 数组拆分为新数组

2021-02-20 12:29发布

问题:

[85, -86, 13, 2, 99, 99, 99, 99, 98, 98, 99, 99, 99, 99, 20, 85, -86, 13, 2, 99, 99, 99, 99, 99, 99, 99,85, 12, 85, -86, 13, 2, 99]

请教,类似这样的数组如何按照85这个数,拆分为多个新数组

如:

[85, -86, 13, 2, 99, 99, 99, 99, 98, 98, 99, 99, 99, 99, 20]

[85, -86, 13, 2, 99, 99, 99, 99, 99, 99, 99]

[85, 12]

[85, -86, 13, 2, 99]

回答1:

public void ArrFun1() {
int[] arr = {85, -86, 13, 2, 99, 99, 99, 99, 98, 98, 99, 99, 99, 99, 20, 85, -86, 13, 2, 99, 99, 99, 99, 99, 99, 99, 85, 12, 85, -86, 13, 2, 99};
String arrStr = Arrays.toString(arr);
System.out.println(arrStr);
List<List<Integer>> list = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 85) {
if (temp.size() > 0) {
list.add(new ArrayList<Integer>(temp));
temp.clear();
}
temp.add(arr[i]);
} else {
temp.add(arr[i]);
}
}
list.add(temp);
System.out.println("===============");
for (List item : list) {
System.out.println(Arrays.toString(item.toArray()));
}
}




回答2:

头铁遍历!



标签: java