System.arraycopy的一些使用。数组的拼接。

来源:互联网 发布:网络著作权侵权 编辑:程序博客网 时间:2024/06/05 23:43

前几天项目中遇到一个的数组拼接的问题。第一个数组是长度变化的,第二个数组是长度固定的。要把第一个数组插入到第二个数组中间去。首先想到的当然是用for循环之类的。可惜本人是学渣小白,对于for循环这种逻辑性的东西一看到就头大。于是就没办法只好各种百度查看有没有简单的方法。然后就找到了System.arraycopy这个东西。System.arraycopy的具体解释可以看这里。然后还是贴代码吧。我这里是把第一个数组插入到第二个数组第六位后面。

ps我省略了for循环输出组合后具体的值。


byte[] a={1,2,3,4,5,6}//长度不固定byte[] b={a,b,c,d,e,f,g,h}//固定byte[] concat = concat(b, a);system.out.println("concat="+concat);public static <T> byte[] concat(byte[] first, byte[] second) {        byte[] c= new byte[first.length+second.length];        System.arraycopy(first, 0, c, 0, first.length);//  abcdefgh000000        System.arraycopy(second, 0, c, 6, second.length);//abcdef12345600        System.arraycopy(first, 6,c, 6+second.length, 2);//{a,b,c,d,e,f,1,2,3,4,5,6,g,h}        return c;    }打印输出concat={a,b,c,d,e,f,1,2,3,4,5,6,g,h}






0 0
原创粉丝点击