Java中動態(tài)地改變數組長度及數組轉Map的代碼實例分享
更新時間:2016年03月22日 08:50:32 作者:Ai2015WER
這篇文章主要介紹了Java中動態(tài)地改變數組長度及數組轉map的代碼分享,其中轉Map利用到了java.util.Map接口,需要的朋友可以參考下
動態(tài)改變數組的長度
/** * 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<a.length; 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", "Tokyo" }, { "France", "Paris" } }; Map countryCapitals = ArrayUtils.toMap(countries); System.out.println("Capital of Japan is " + countryCapitals.get("Japan")); System.out.println("Capital of France is " + countryCapitals.get("France")); } }
相關文章
springboot 實現mqtt物聯(lián)網的示例代碼
這篇文章主要介紹了springboot 實現mqtt物聯(lián)網,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03FutureTask為何單個任務僅執(zhí)行一次原理解析
這篇文章主要為大家介紹了FutureTask為何單個任務僅執(zhí)行一次原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11