
java数组拆分
问题:
如何将一个数组(例如:[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)拆分为多个新数组?
答案:
立即学习“”;
可以使用如下方法将数组拆分为新数组:
public static void arrfun(int[] arr, int splitvalue) {
list<list<integer>> list = new arraylist<>();
list<integer> temp = new arraylist<>();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == splitvalue) {
if (!temp.isempty()) {
list.add(new arraylist<>(temp));
temp.clear();
}
temp.add(arr[i]);
} else {
temp.add(arr[i]);
}
}
list.add(temp);
system.out.println("拆分后的数组:");
for (list<integer> item : list) {
system.out.println(arrays.tostring(item.toarray()));
}
}
登录后复制
示例:
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};
arrfun(arr, 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]
登录后复制
以上就是如何使用Java将一个数组按照特定元素拆分为多个新数组?的详细内容,更多请关注IDCBABY其它相关文章!
