Java中动态地改变数组长度及数组转Map的代码实例分享
动态改变数组的长度
/***Reallocatesanarraywithanewsize,andcopiesthecontents
**oftheoldarraytothenewarray.
**@paramoldArraytheoldarray,tobereallocated.
**@paramnewSizethenewarraysize.
**@returnAnewarraywiththesamecontents.
**/
privatestaticObjectresizeArray(ObjectoldArray,intnewSize){
intoldSize=java.lang.reflect.Array.getLength(oldArray);
ClasselementType=oldArray.getClass().getComponentType();
ObjectnewArray=java.lang.reflect.Array.newInstance(
elementType,newSize);
intpreserveLength=Math.min(oldSize,newSize);
if(preserveLength>0)
System.arraycopy(oldArray,0,newArray,0,preserveLength);
returnnewArray;}
//TestroutineforresizeArray().
publicstaticvoidmain(String[]args){
int[]a={1,2,3};
a=(int[])resizeArray(a,5);
a[3]=4;
a[4]=5;
for(inti=0;i<a.length;i++)
System.out.println(a[i]);
}
代码只是实现基础方法,详细处理还需要你去Coding哦>>
把Array转换成Map
importjava.util.Map;
importorg.apache.commons.lang.ArrayUtils;
publicclassMain{
publicstaticvoidmain(String[]args){
String[][]countries={{"UnitedStates","NewYork"},
{"UnitedKingdom","London"},
{"Netherland","Amsterdam"},
{"Japan","Tokyo"},
{"France","Paris"}};
MapcountryCapitals=ArrayUtils.toMap(countries);
System.out.println("CapitalofJapanis"+countryCapitals.get("Japan"));
System.out.println("CapitalofFranceis"+countryCapitals.get("France"));
}
}热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短