怎么把数组分割成2个数组,每个数组的长度是原始数组的1/2
要完整的代码和注释。
2条回答 默认 最新
关注 https://blog.csdn.net/qq_34926773/article/details/94437175
List<String> list = new ArrayList<>(); for (int i = 0; i < 5; i++) { list.add("China"+i); } CommUtil<String> util = new CommUtil<String>(); List<List<String>> resultList = util.subListBySegment(list, 2); for (int i = 0; i < resultList.size(); i++) { List<String> tempList = resultList.get(i); for (int j = 0; j < tempList.size(); j++) { System.out.print(tempList.get(j)); } }
public class CommUtil<T> { public List<List<T>> subListBySegment(List<T> data, int segments) { List<List<T>> result = new ArrayList<>(); int size = data.size();// 数据长度 if (size > 0 && segments > 0) {// segments == 0 ,不需要分隔 int count = size / segments;// 每段数量 List<T> cutList = null;// 每段List for (int i = 0; i < segments; i++) { if (i == segments - 1) { cutList = data.subList(count * i, size); } else { cutList = data.subList(count * i, count * (i + 1)); } result.add(cutList); } } else { result.add(data); } return result; } public List<List<T>> subListByCount(List<T> data, int count) { List<List<T>> result = new ArrayList<>(); int size = data.size();// 数据长度 if (size > 0 && count > 0) { int segments = size / count;// 商 /** * 1.整除, 即分隔为segments 段 * 2.除不尽,即分隔为segments + 1 段 */ segments = size % count == 0 ? segments : segments + 1; // 段数 List<T> cutList = null;// 每段List for (int i = 0; i < segments; i++) { if (i == segments - 1) { cutList = data.subList(count * i, size); } else { cutList = data.subList(count * i, count * (i + 1)); } result.add(cutList); } } else { result.add(data); } return result; } }
解决 无用评论 打赏 举报
悬赏问题
- ¥15 三菱伺服电机按启动按钮有使能但不动作
- ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
- ¥15 js,页面2返回页面1时定位进入的设备
- ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
- ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
- ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
- ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
- ¥20 腾讯企业邮箱邮件可以恢复么
- ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
- ¥15 错误 LNK2001 无法解析的外部符号