根据特定元素拆分java数组
本例中,要求根据元素85将数组拆分成多个新数组。为此,可以使用以下过程:
以下java代码实现了这个过程:
import java.util.arraylist;
import java.util.list;
public class arraysplitter {
public static void main(string[] args) {
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};
splitarray(arr, 85);
}
public static void splitarray(int[] arr, int target) {
list> result = new arraylist<>();
list temp = new arraylist<>();
for (int i : arr) {
if (i == target) {
if (!temp.isempty()) {
result.add(new arraylist<>(temp));
temp.clear();
}
temp.add(i);
} else {
temp.add(i);
}
}
result.add(temp);
for (list list : result) {
system.out.println(list);
}
}
}
输出:
[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]