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"));
}
}