java 数组如何按指定元素拆分
给定一个数组,如何将其按照特定元素(例如 85)拆分为多个新数组?
public void mymethod(int[] arr, int splitvalue) { list<list<integer>> result = new arraylist<>(); list<integer> temp = new arraylist<>(); for (int num : arr) { if (num == splitvalue) { if (!temp.isempty()) { result.add(new arraylist<>(temp)); temp.clear(); } temp.add(num); } else { temp.add(num); } } result.add(temp); for (list<integer> subarray : result) { system.out.println(arrays.tostring(subarray.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}; mymethod(arr, 85);
输出:
立即学习“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]
以上就是如何使用Java将一个数组按照指定元素拆分成多个新数组?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号