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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
java 将byte中的有效长度转换为String的实例代码
下面小编就为大家带来一篇java 将byte中的有效长度转换为String的实例代码。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2016-11-11
Java concurrency之公平锁(一)_动力节点Java学院整理
这篇文章主要为大家详细介绍了Java concurrency之公平锁的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-06-06


最新评论