集合框架

Java 教程 · 第 5 章 · 6 次浏览

Java 的集合框架(Collections Framework)是处理数据的核心工具。以前学的数组长度固定,集合可以动态增删。

常用集合

  • List:有序可重复。ArrayList 底层数组(查快)、LinkedList 链表(增删快)
  • Set:无序不重复。HashSet 哈希实现
  • Map:键值对。HashMap 最常用,LinkedHashMap 保序,TreeMap 按键排序

泛型

集合默认可以放任何对象,用泛型限定类型更安全:List<String> 只能放字符串。

遍历

for-each 循环遍历 List/Set,Map 遍历 entrySet。

代码示例

import java.util.*;

public class CollectionsDemo {
    public static void main(String[] args) {
        // List
        List<String> names = new ArrayList<>();
        names.add("张三");
        names.add("李四");
        names.remove("张三");
        for (String n : names) System.out.println(n);

        // Map
        Map<String, Integer> scores = new HashMap<>();
        scores.put("语文", 90);
        scores.put("数学", 95);
        System.out.println(scores.get("数学"));

        for (Map.Entry<String, Integer> e : scores.entrySet()) {
            System.out.println(e.getKey() + ": " + e.getValue());
        }

        // Set
        Set<Integer> ids = new HashSet<>();
        ids.add(1); ids.add(2); ids.add(1);   // 重复的 1 不会加进去
        System.out.println(ids.size());       // 2
    }
}