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"));
}
}热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下