Java中动态地改变数组长度及数组转Map的代码实例分享

网友投稿 194 2023-07-20


Java中动态地改变数组长度及数组转Map的代码实例分享

动态改变数组的长度

/** * Reallocates an array with a new size, and copies the contents

* * of the old array to the new array.

* * @param oldArray the old array, to be reallocated.

* * @param newSize the new array size.

* * @return A new array with the same contents.

* */

private static Object resizeArray (Object oldArray, int newSize) {

int oldSize = java.lang.reflect.Array.getLength(oldArray);

Class elementType = oldArray.getClass().getComponentType();

Object newArray = java.lang.reflect.Array.newInstance(

elementType,newSize);

int preserveLength = Math.min(oldSize,newSize);

if (preserveLength > 0)

System.arraycopy (oldArray,0,newArray,0,preserveLength);

return newArray; }

// Test routine for resizeArray().

public static void main (String[] args) {

int[] a = {1,2,3};

a = (int[])resizeArray(a,5);

a[3] = 4;

a[4] = 5;

for (int i=0; i

System.out.println (a[i]);

}

代码只是实现基础方法,详细处理还需要你去Coding哦>>

把 Array 转换成 Map

import java.util.Map;

import org.apache.commons.lang.ArrayUtils;

public class Main {

public static void main(String[] args) {

String[][] countries = { { "United States", "New York" },

{ "United Kingdom", "London" },

{ "Netherland", "Amsterdam" },

{ "Japan", "Tokyohttp://" },

{ "France", "Paris" http://} };

Map countryCapitals = ArrayUtils.toMap(countries);

System.out.println("Capital of Japan is " + cohttp://untryCapitals.get("Japan"));

System.out.println("Capital of France is " + countryCapitals.get("France"));

}

}

System.out.println (a[i]);

}

代码只是实现基础方法,详细处理还需要你去Coding哦>>

把 Array 转换成 Map

import java.util.Map;

import org.apache.commons.lang.ArrayUtils;

public class Main {

public static void main(String[] args) {

String[][] countries = { { "United States", "New York" },

{ "United Kingdom", "London" },

{ "Netherland", "Amsterdam" },

{ "Japan", "Tokyohttp://" },

{ "France", "Paris" http://} };

Map countryCapitals = ArrayUtils.toMap(countries);

System.out.println("Capital of Japan is " + cohttp://untryCapitals.get("Japan"));

System.out.println("Capital of France is " + countryCapitals.get("France"));

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java实例化类详解
下一篇:使用getBoundingClientRect方法实现简洁的sticky组件的方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~