Skip to content

📦 数组与集合

数组

数组声明和初始化

java
// 方式1:声明后初始化
int[] arr1 = new int[5];  // 长度为 5 的数组,默认值为 0

// 方式2:直接初始化
int[] arr2 = {1, 2, 3, 4, 5};

// 方式3:另一种初始化方式
int[] arr3 = new int[]{1, 2, 3, 4, 5};

// 多维数组
int[][] matrix = new int[3][4];  // 3行4列的二维数组
int[][] matrix2 = {{1, 2}, {3, 4}, {5, 6}};

数组操作

java
int[] arr = {1, 2, 3, 4, 5};

// 访问元素
int first = arr[0];  // 1
arr[0] = 10;         // 修改元素

// 数组长度
int length = arr.length;  // 5

// 遍历数组
for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);
}

// 增强 for 循环
for (int num : arr) {
    System.out.println(num);
}

Collection 接口

Collection 主要方法

java
Collection<String> collection = new ArrayList<>();

// 添加元素
collection.add("元素1");
collection.add("元素2");

// 删除元素
collection.remove("元素1");

// 检查包含
boolean contains = collection.contains("元素2");

// 大小
int size = collection.size();

// 是否为空
boolean isEmpty = collection.isEmpty();

// 清空
collection.clear();

// 遍历
for (String item : collection) {
    System.out.println(item);
}

List 接口

ArrayList

java
// 创建 ArrayList
List<String> list = new ArrayList<>();

// 添加元素
list.add("元素1");
list.add("元素2");
list.add(0, "元素0");  // 在指定位置插入

// 获取元素
String first = list.get(0);

// 修改元素
list.set(0, "新元素");

// 删除元素
list.remove(0);  // 按索引删除
list.remove("元素1");  // 按值删除

// 查找
int index = list.indexOf("元素2");
boolean contains = list.contains("元素1");

// 遍历
for (String item : list) {
    System.out.println(item);
}

// 使用迭代器
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

LinkedList

java
// 创建 LinkedList
List<String> list = new LinkedList<>();

// LinkedList 特有方法
LinkedList<String> linkedList = new LinkedList<>();
linkedList.addFirst("第一个");
linkedList.addLast("最后一个");
String first = linkedList.getFirst();
String last = linkedList.getLast();
linkedList.removeFirst();
linkedList.removeLast();

Vector(已过时)

java
// Vector 是线程安全的,但性能较差,不推荐使用
Vector<String> vector = new Vector<>();

Set 接口

HashSet

java
// 创建 HashSet(无序,不重复)
Set<String> set = new HashSet<>();

// 添加元素
set.add("元素1");
set.add("元素2");
set.add("元素1");  // 重复元素,不会添加

// 检查包含
boolean contains = set.contains("元素1");

// 删除元素
set.remove("元素1");

// 遍历(无序)
for (String item : set) {
    System.out.println(item);
}

LinkedHashSet

java
// LinkedHashSet(有序,不重复)
Set<String> set = new LinkedHashSet<>();
// 按插入顺序存储

TreeSet

java
// TreeSet(有序,不重复,按自然顺序或比较器排序)
Set<String> set = new TreeSet<>();
// 自动排序

// 自定义比较器
Set<Person> personSet = new TreeSet<>((p1, p2) -> 
    p1.getName().compareTo(p2.getName()));

Map 接口

HashMap

java
// 创建 HashMap
Map<String, Integer> map = new HashMap<>();

// 添加键值对
map.put("key1", 1);
map.put("key2", 2);

// 获取值
Integer value = map.get("key1");

// 检查键是否存在
boolean containsKey = map.containsKey("key1");

// 检查值是否存在
boolean containsValue = map.containsValue(1);

// 删除
map.remove("key1");

// 大小
int size = map.size();

// 遍历
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

// 遍历键
for (String key : map.keySet()) {
    System.out.println(key);
}

// 遍历值
for (Integer value : map.values()) {
    System.out.println(value);
}

LinkedHashMap

java
// LinkedHashMap(有序,按插入顺序)
Map<String, Integer> map = new LinkedHashMap<>();

TreeMap

java
// TreeMap(有序,按键的自然顺序或比较器排序)
Map<String, Integer> map = new TreeMap<>();

集合转换

数组转集合

java
// 数组转 List
String[] arr = {"a", "b", "c"};
List<String> list = Arrays.asList(arr);

// 注意:Arrays.asList() 返回的 List 大小固定,不能添加或删除
// 如果需要可变的 List
List<String> mutableList = new ArrayList<>(Arrays.asList(arr));

集合转数组

java
// List 转数组
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
String[] arr = list.toArray(new String[0]);

集合互转

java
// List 转 Set(去重)
List<String> list = Arrays.asList("a", "b", "a", "c");
Set<String> set = new HashSet<>(list);

// Set 转 List
List<String> list2 = new ArrayList<>(set);

集合工具类 Collections

java
List<Integer> list = new ArrayList<>();
list.add(3);
list.add(1);
list.add(4);

// 排序
Collections.sort(list);

// 反转
Collections.reverse(list);

// 打乱
Collections.shuffle(list);

// 查找(必须已排序)
int index = Collections.binarySearch(list, 3);

// 最大值和最小值
int max = Collections.max(list);
int min = Collections.min(list);

// 填充
Collections.fill(list, 0);

// 频率
int frequency = Collections.frequency(list, 3);

// 同步包装(线程安全)
List<String> synchronizedList = Collections.synchronizedList(new ArrayList<>());

Stream API(Java 8+)

java
List<String> list = Arrays.asList("apple", "banana", "cherry");

// 过滤
List<String> filtered = list.stream()
    .filter(s -> s.startsWith("a"))
    .collect(Collectors.toList());

// 映射
List<String> mapped = list.stream()
    .map(String::toUpperCase)
    .collect(Collectors.toList());

// 排序
List<String> sorted = list.stream()
    .sorted()
    .collect(Collectors.toList());

// 去重
List<String> distinct = list.stream()
    .distinct()
    .collect(Collectors.toList());

// 计数
long count = list.stream().count();

// 查找
Optional<String> first = list.stream().findFirst();

完整示例

java
public class CollectionExample {
    public static void main(String[] args) {
        // ArrayList 示例
        List<String> list = new ArrayList<>();
        list.add("元素1");
        list.add("元素2");
        System.out.println("List: " + list);
        
        // HashSet 示例
        Set<String> set = new HashSet<>();
        set.add("元素1");
        set.add("元素2");
        set.add("元素1");  // 重复,不会添加
        System.out.println("Set: " + set);
        
        // HashMap 示例
        Map<String, Integer> map = new HashMap<>();
        map.put("key1", 1);
        map.put("key2", 2);
        System.out.println("Map: " + map);
        
        // Stream API 示例
        List<String> filtered = list.stream()
            .filter(s -> s.contains("1"))
            .collect(Collectors.toList());
        System.out.println("Filtered: " + filtered);
    }
}

性能比较

List 性能

操作ArrayListLinkedList
随机访问O(1)O(n)
插入(末尾)O(1)O(1)
插入(中间)O(n)O(1)
删除O(n)O(1)

Set 性能

  • HashSet:O(1) 平均查找时间
  • TreeSet:O(log n) 查找时间
  • LinkedHashSet:O(1) 平均查找时间,保持插入顺序

Map 性能

  • HashMap:O(1) 平均查找时间
  • TreeMap:O(log n) 查找时间
  • LinkedHashMap:O(1) 平均查找时间,保持插入顺序

最佳实践

1. 选择合适的集合类型

java
// 需要有序且允许重复 → ArrayList
List<String> list = new ArrayList<>();

// 需要去重 → HashSet
Set<String> set = new HashSet<>();

// 需要键值对 → HashMap
Map<String, Integer> map = new HashMap<>();

// 需要排序 → TreeSet 或 TreeMap
Set<String> sortedSet = new TreeSet<>();

2. 使用泛型

java
// ✅ 好的做法:使用泛型
List<String> list = new ArrayList<>();

// ❌ 不好的做法:不使用泛型
List list = new ArrayList();  // 不推荐

3. 遍历集合

java
// ✅ 推荐:增强 for 循环
for (String item : list) {
    System.out.println(item);
}

// ✅ 推荐:Stream API(Java 8+)
list.stream().forEach(System.out::println);

下一步

掌握了数组与集合后,可以继续学习:


💡 提示:选择合适的集合类型可以提高程序性能,理解不同集合的特点很重要