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)拆分为多个新数组?
答案:
立即学习“Java免费学习笔记(深入)”;
可以使用如下方法将数组拆分为新数组:
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将一个数组按照特定元素拆分为多个新数组?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号