Java中動態(tài)地改變數(shù)組長度及數(shù)組轉(zhuǎn)Map的代碼實例分享
更新時間:2016年03月22日 08:50:32 作者:Ai2015WER
這篇文章主要介紹了Java中動態(tài)地改變數(shù)組長度及數(shù)組轉(zhuǎn)map的代碼分享,其中轉(zhuǎn)Map利用到了java.util.Map接口,需要的朋友可以參考下
動態(tài)改變數(shù)組的長度
/** * 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]);
}
代碼只是實現(xiàn)基礎(chǔ)方法,詳細處理還需要你去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)文章
Mybatis-plus中的@EnumValue注解使用詳解
這篇文章主要介紹了Mybatis-plus中的@EnumValue注解使用詳解,在PO類中,如果我們直接使用枚舉類型去映射數(shù)據(jù)庫的對應字段保存時,往往就會因為類型不匹配導致映射失敗,Mybatis-plus提供了一種解決辦法,就是使用@EnumValue注解,需要的朋友可以參考下2024-02-02
Java中的Random和ThreadLocalRandom詳細解析
這篇文章主要介紹了Java中的Random和ThreadLocalRandom詳細解析,Random 類用于生成偽隨機數(shù)的流, 該類使用48位種子,其使用線性同余公式進行修改,需要的朋友可以參考下2024-01-01
SSH框架網(wǎng)上商城項目第25戰(zhàn)之使用java email給用戶發(fā)送郵件
這篇文章主要為大家詳細介紹了SSH框架網(wǎng)上商城項目第25戰(zhàn)之使用java email給用戶發(fā)送郵件,感興趣的小伙伴們可以參考一下2016-06-06

