3358 freewind.me/blog/2011 09 22/350.html
在Java中,如何将两个String[]合并为一个?
看起来是个很简单的问题。 但是,如何才能有效、简洁地编写代码是值得思考的。 这里介绍四种方法,请参考选择。
一、apache-commons这是最简单的方法。 apache-commons包含Arrayutils.addall(Object[]、object () ) )方法,可以在一行中完成。
String[] both=(String[] ) array utils.addall (第一,第二个); 所有其他东西都需要自己调用jdk提供的方法进行包装。
为了方便起见,定义工具方法concat。 两个数可以组合起来。
staticstring [ ] concat (string [ ] first,String[] second ) )是通用的,并且在可能的情况下使用通用类型进行定义。 这样不仅可以使用string[],还可以使用其他类型的数组。
statict[]concat(t[]first,T[] second ) }当然,如果jdk不支持通用性或不可用,可以手动将t替换为字符串。
二、system.arraycopy(staticstring ) (concat ) string ) (a,string ) (b ) (string ) ) c=newstring ) a.lengthb.b sstring 系统. arraycopy (b,0,c,a.length,b.length ); 返回c; }使用如下。
string [ ] both=concat (第一个,第二个); 三、Arrays.copyOf () java6有一个名为Arrays.copyOf ()的通用函数方法。 利用这个,可以写更通用的集成方法。
公共静态t [ ] concat (t [ ] first,T[] second ) t[]result=Arrays.copyof(first,first.length second.length ) 返回结果; }合并多个时,可以写如下:
公共静态t [ ] concat all (t [ ] first,T[]. rest ) { int totalLength=first.length; for(t[]array:rest ) { totalLength =array.length; } t [ ] result=arrays.copy of (第一个,totalLength ); int offset=first.length; for(t[]array:rest )系统. arraycopy (array,0,result,offset,array.length ); offset =array.length; }返回结果; }使用如下。
string [ ] both=concat (第一个,第二个); string[]more=concat(first,second,third,fourth ); 四. Array.newInstance也可以使用Array.newInstance生成数组。
私有状态[ ] concat (t [ ] a,T[] b ) { final int alen=a.length; final int blen=b.length; if(Alen==0) { return b; (if ) blen==0) ) { return a; }finalt[]result=(t () Java.lang.reflect.array.new instance (a.getclass ).getComponentType ) ),Alenbllass system.arraycopy(b,0,result,alen,blen ); 返回结果; }