java中合拼数组的三个方法

介绍下java中三个合拼数组的方法

1) 使用apache common包

public static void main(String[] args) {

String[] s1 = new String[]{"a", "b", "c"};
String[] s2 = new String[]{"d", "e", "f"};

String[] result = ArrayUtils.addAll(s1, s2);

System.out.println(Arrays.toString(result));

int [] int1 = new int[]{1,2,3};
int[] int2 = new int[]{4,5,6};

int[] result2 = ArrayUtils.addAll(int1, int2);

System.out.println(Arrays.toString(result2));


2) 单纯的编写方法

public static void main(String[] args) {

String[] s1 = new String[]{"a", "b", "c"};
String[] s2 = new String[]{"d", "e", "f"};
String[] s3 = new String[]{"g", "h", "i"};

String[] result = joinArrayGeneric(s1, s2, s3);

System.out.println(Arrays.toString(result));

int[] int1 = new int[]{1, 2, 3};
int[] int2 = new int[]{4, 5, 6};
int[] int3 = new int[]{7, 8, 9};

int[] result2 = joinArray(int1, int2, int3);

System.out.println(Arrays.toString(result2));

}

static <T> T[] joinArrayGeneric(T[]... arrays) {
int length = 0;
for (T[] array : arrays) {
length += array.length;
}

//T[] result = new T[length];
final T[] result = (T[]) Array.newInstance(arrays[0].getClass().getComponentType(), length);

int offset = 0;
for (T[] array : arrays) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}

return result;
}

static int[] joinArray(int[]... arrays) {
int length = 0;
for (int[] array : arrays) {
length += array.length;
}

final int[] result = new int[length];

int offset = 0;
for (int[] array : arrays) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}

return result;
}

//create other overloaded primitive type - long, double...
//static long[] joinArray(long[]... arrays)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值