在Java中,HashMap是一個內(nèi)置的數(shù)據(jù)結(jié)構(gòu),用于存儲鍵值對。要定義一個HashMap數(shù)組,首先需要確定數(shù)組的大小,然后為每個元素創(chuàng)建一個HashMap實例。以下是一個示例:
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// 定義一個大小為3的HashMap數(shù)組
HashMap<String, Integer>[] hashMapArray = new HashMap[3];
// 為數(shù)組的每個元素創(chuàng)建一個HashMap實例
for (int i = 0; i < hashMapArray.length; i++) {
hashMapArray[i] = new HashMap<>();
}
// 使用HashMap數(shù)組
hashMapArray[0].put("key1", 1);
hashMapArray[1].put("key2", 2);
hashMapArray[2].put("key3", 3);
// 輸出HashMap數(shù)組的內(nèi)容
for (int i = 0; i < hashMapArray.length; i++) {
System.out.println("HashMap " + (i + 1) + ": " + hashMapArray[i]);
}
}
}
這個示例創(chuàng)建了一個大小為3的HashMap數(shù)組,并為每個元素添加了一些鍵值對。然后,它遍歷數(shù)組并輸出每個HashMap的內(nèi)容。