用ChatGPT搞懂ArrayList、HashMap,一次打通資料儲存觀念!
在寫 Java 程式的時候,我們常常需要「存很多資料」
最一開始我們用 陣列(Array),但陣列有大小限制、不能動態新增刪除,這時就輪到集合(Collection)登場啦!
今天來看看 ChatGPT 怎麼幫我們快速理解 ArrayList 跟 HashMap
一、陣列與集合的差別是什麼?
類型 / 特點 / 限制
陣列 (Array) / 固定長度、同類型元素 / 不能動態新增刪除
ArrayList / 可變長度、可新增刪除元素 / 只能存物件型別
HashMap / 以「鍵值對 (key-value)」形式儲存資料 / Key 不可重複
ChatGPT 小提示:
陣列像是排好的座位表,先決定有幾個位子;
ArrayList 像是彈性椅區,隨時可以多放幾張椅子;
HashMap 則像是資料對照表——有名字(key)就能找到對應資料(value)
二、ArrayList 範例:學生名單
假設我們要記錄一個班級的學生名單:
public class Main {
public static void main(String[] args) {
ArrayList<String> students = new ArrayList<>();
students.add("小明");
students.add("小美");
students.add("阿華");
System.out.println("學生名單:" + students);
// 移除一位學生
students.remove("小美");
System.out.println("更新後名單:" + students);
// 取出第一位學生
System.out.println("第一位學生:" + students.get(0));
}
}
ChatGPT的說明範例:
1.ArrayList.add() 是新增元素
2.remove() 是刪除
3.get(index) 是取出特定位置的資料
如果你不確定程式為什麼錯,
只要貼給 ChatGPT:「這段ArrayList程式出現IndexOutOfBoundsException,幫我找出原因」
它會告訴你是因為取出的索引超出範圍,並幫你改好!
三、HashMap 範例:學號與姓名對照表
public class Main {
public static void main(String[] args) {
HashMap<String, String> studentMap = new HashMap<>();
studentMap.put("S001", "小明");
studentMap.put("S002", "小美");
studentMap.put("S003", "阿華");
System.out.println("學號對照表:" + studentMap);
// 透過學號查詢學生姓名
System.out.println("S002 的學生是:" + studentMap.get("S002"));
// 移除一位學生
studentMap.remove("S003");
System.out.println("更新後對照表:" + studentMap);
}
}
ChatGPT 的說明:
1.HashMap 是「一組一組」的資料(key → value)
2.put() 是新增或更新資料
3.get() 是用 key 查 value
4.remove() 是刪除資料
四、ChatGPT幫忙學習的方法
不懂為什麼用ArrayList比用陣列好?
輸入:
幫我比較Java陣列和ArrayList的差別,並舉實際例子
想練習HashMap?
幫我出3題關於 HashMap 的練習題,附答案
AI 不只會幫你解釋,還會當你的家教出題給你練 💪
今日小結
陣列:固定長度
ArrayList:彈性可變、順序儲存
HashMap:以鍵值對形式管理資料
再搭配 ChatGPT 的即時解說與範例,
就算是 OOP 新手,也能快速理解資料結構的實際用途!
今日挑戰
用ChatGPT請它幫你:
寫一段Java程式,用HashMap儲存三個商品名稱與價格,再計算平均價格
讓AI幫你改程式、講解思路,
你會發現「學習 + 實作 + Debug」一次完成