Java中動(dòng)態(tài)地改變數(shù)組長(zhǎng)度及數(shù)組轉(zhuǎn)Map的代碼實(shí)例分享
動(dòng)態(tài)改變數(shù)組的長(zhǎng)度
/** * 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]); }
代碼只是實(shí)現(xiàn)基礎(chǔ)方法,詳細(xì)處理還需要你去Coding哦>>
把 Array 轉(zhuǎn)換成 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")); } }
相關(guān)文章
springboot 實(shí)現(xiàn)mqtt物聯(lián)網(wǎng)的示例代碼
這篇文章主要介紹了springboot 實(shí)現(xiàn)mqtt物聯(lián)網(wǎng),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03FutureTask為何單個(gè)任務(wù)僅執(zhí)行一次原理解析
這篇文章主要為大家介紹了FutureTask為何單個(gè)任務(wù)僅執(zhí)行一次原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11Gateway網(wǎng)關(guān)自定義攔截器的不可重復(fù)讀取數(shù)據(jù)問(wèn)題
這篇文章主要介紹了Gateway網(wǎng)關(guān)自定義攔截器的不可重復(fù)讀取數(shù)據(jù)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08對(duì)象轉(zhuǎn)Json字符串時(shí)如何忽略指定屬性
這篇文章主要介紹了對(duì)象轉(zhuǎn)Json字符串時(shí)如何忽略指定屬性,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08Java中關(guān)鍵字synchronized的使用方法詳解
synchronized關(guān)鍵字可以作為函數(shù)的修飾符,也可作為函數(shù)內(nèi)的語(yǔ)句,也就是平時(shí)說(shuō)的同步方法和同步語(yǔ)句塊,下面這篇文章主要給大家介紹了關(guān)于Java中synchronized使用的相關(guān)資料,需要的朋友可以參考下2021-08-08