Java连接合并2个数组(Array)的5种方法例子
更新时间:2023年12月14日 16:18:08 作者:choice`
最近在写代码时遇到了需要合并两个数组的需求,突然发现以前没用过,于是研究了一下合并数组的方式,这篇文章主要给大家介绍了关于Java连接合并2个数组(Array)的5种方法,需要的朋友可以参考下
1、使用泛型方法和System.arraycopy实现
T可以是基础类型,也是类类型
public static <T> T concatenate(T a, T b) { if (!a.getClass().isArray() || !b.getClass().isArray()) { throw new IllegalArgumentException(); } Class<?> resCompType; Class<?> aCompType = a.getClass().getComponentType(); Class<?> bCompType = b.getClass().getComponentType(); if (aCompType.isAssignableFrom(bCompType)) { resCompType = aCompType; } else if (bCompType.isAssignableFrom(aCompType)) { resCompType = bCompType; } else { throw new IllegalArgumentException(); } int aLen = Array.getLength(a); int bLen = Array.getLength(b); @SuppressWarnings("unchecked") T result = (T) Array.newInstance(resCompType, aLen + bLen); System.arraycopy(a, 0, result, 0, aLen); System.arraycopy(b, 0, result, aLen, bLen); return result; }
2、使用ArrayUtils.addAll实现
String[] both = (String[])ArrayUtils.addAll(first, second);
3、不使用System.arraycopy实现
static String[] concat(String[]... arrays) { int length = 0; for (String[] array : arrays) { length += array.length; } String[] result = new String[length]; int pos = 0; for (String[] array : arrays) { for (String element : array) { result[pos] = element; pos++; } } return result; }
4、使用ObjectArrays.concat实现
String[] both = ObjectArrays.concat(first, second, String.class);
5、使用Arrays.copyOf()实现
public static <T> T[] concatAll(T[] first, T[]... rest) { int totalLength = first.length; for (T[] array : rest) { totalLength += array.length; } T[] result = Arrays.copyOf(first, totalLength); int offset = first.length; for (T[] array : rest) { System.arraycopy(array, 0, result, offset, array.length); offset += array.length; } return result; }
总结
到此这篇关于Java连接合并2个数组(Array)的5种方法例子的文章就介绍到这了,更多相关Java连接合并数组Array内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Spring Boot + Kotlin整合MyBatis的方法教程
前几天由于工作需要,便开始学习了kotlin,java基础扎实学起来也还算比较快,对于kotlin这个编程语言自然是比java有趣一些,下面这篇文章主要给大家介绍了关于Spring Boot + Kotlin整合MyBatis的方法教程,需要的朋友可以参考下。2018-01-01基于HttpServletRequest 相关常用方法的应用
本篇文章小编为大家介绍,基于HttpServletRequest 相关常用方法的应用,需要的朋友参考下2013-04-04记一次Maven项目改造成SpringBoot项目的过程实践
本文主要介绍了Maven项目改造成SpringBoot项目的过程实践,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2022-03-03Spring Data JPA的Audit功能审计数据库的变更
数据库审计是指当数据库有记录变更时,可以记录数据库的变更时间和变更人等,这样以后出问题回溯问责也比较方便,本文讨论Spring Data JPA审计数据库变更问题,感兴趣的朋友一起看看吧2021-06-06
最新评论