Java 數組長度固定,無法直接擴容。本文提供兩個實用工具方法:基於反射的數組動態擴容,以及利用 Apache Commons Lang 將二維數組轉換為 Map。
通過 java.lang.reflect.Array 創建新數組並複製原有內容:
/**
* 重新分配數組大小並保留原有內容
* @param oldArray 原數組
* @param newSize 新大小
* @return 新數組
*/
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;
}
// 測試代碼
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]);
}
}
使用 org.apache.commons.lang.ArrayUtils.toMap 快速轉換:
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"));
}
}
resizeArray 返回 Object,調用處需強制轉型。ArrayUtils.toMap 要求二維數組每個子數組長度至少為 2,第一個元素作為 Key,第二個作為 Value。ArrayList 或 Vector。本文提供的兩個代碼片段解決了 Java 數組固定長度與數組轉集合的常見需求,代碼簡潔且可直接應用於項目中。