最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java List 使用舉例(從入門到精通)

 更新時間:2025年08月14日 10:58:36   作者:我愛Jack  
本文系統(tǒng)講解Java List,涵蓋基礎(chǔ)概念、核心特性、常用實(shí)現(xiàn)(如ArrayList、LinkedList)及性能對比,介紹創(chuàng)建、操作、遍歷方法,結(jié)合實(shí)戰(zhàn)案例,提供選擇策略和優(yōu)化技巧,幫助高效使用List,感興趣的朋友跟隨小編一起看看吧

一、List 基礎(chǔ)概念

1.1 什么是 List?

List 就像是一個智能書架

  • 可以按順序存放書籍(元素)
  • 每本書都有固定位置(索引)
  • 可以隨時添加、取出或重新排列書籍
// 創(chuàng)建一個書架(List)
List<String> bookshelf = new ArrayList<>();

1.2 List 的核心特性

特性說明生活類比
有序性元素按添加順序存儲書架上的書按放入順序排列
可重復(fù)允許相同元素多次出現(xiàn)同一本書可以有多個副本
索引訪問通過位置編號快速獲取元素通過書架編號找書
動態(tài)擴(kuò)容自動調(diào)整存儲空間智能書架自動擴(kuò)展

1.3 List 家族成員

二、List 基本操作

2.1 創(chuàng)建 List 的三種方式

// 方式1:標(biāo)準(zhǔn)創(chuàng)建(推薦)
List<String> fruits = new ArrayList<>();
// 方式2:快速初始化
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// 方式3:不可變列表(Java 9+)
List<String> colors = List.of("紅", "綠", "藍(lán)");

2.2 添加元素 - 豐富你的書架

fruits.add("蘋果");     // 末尾添加
fruits.add(0, "香蕉");  // 指定位置插入
fruits.addAll(Arrays.asList("橙子", "葡萄")); // 批量添加
System.out.println(fruits); 
// 輸出: [香蕉, 蘋果, 橙子, 葡萄]

2.3 訪問元素 - 查找書籍

// 獲取單個元素
String firstFruit = fruits.get(0); // "香蕉"
// 檢查元素是否存在
boolean hasApple = fruits.contains("蘋果"); // true
// 查找元素位置
int appleIndex = fruits.indexOf("蘋果"); // 1

2.4 修改元素 - 替換書籍

// 替換指定位置的元素
String oldFruit = fruits.set(1, "青蘋果");
System.out.println("被替換的水果: " + oldFruit); // "蘋果"

2.5 刪除元素 - 清理書架

// 按索引刪除
String removed = fruits.remove(0); // 刪除"香蕉"
// 按元素值刪除
boolean isRemoved = fruits.remove("葡萄"); // true
// 批量刪除
fruits.removeAll(Arrays.asList("橙子", "青蘋果"));
// 清空書架
fruits.clear();

三、遍歷 List 的多種方式

3.1 基礎(chǔ)遍歷方法

// 1. for循環(huán)(索引訪問)
for (int i = 0; i < fruits.size(); i++) {
    System.out.println((i+1) + ". " + fruits.get(i));
}
// 2. 增強(qiáng)for循環(huán)
for (String fruit : fruits) {
    System.out.println(fruit);
}

3.2 使用迭代器

// 3. Iterator遍歷
Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
    String fruit = iterator.next();
    if (fruit.equals("葡萄")) {
        iterator.remove(); // 安全刪除
    }
}

3.3 Java 8+ 高級遍歷

// 4. forEach方法
fruits.forEach(fruit -> System.out.println(fruit));
// 5. 方法引用
fruits.forEach(System.out::println);
// 6. 并行流遍歷(大數(shù)據(jù)量)
fruits.parallelStream().forEach(fruit -> {
    // 并行處理邏輯
});

3.4 遍歷性能對比

遍歷方式10萬元素耗時適用場景
for循環(huán)5ms需要索引時
增強(qiáng)for7ms簡單遍歷
Iterator8ms需要刪除元素時
forEach10ms函數(shù)式編程
并行流3ms大數(shù)據(jù)量處理

四、List 高級操作

4.1 排序操作

List<Integer> numbers = Arrays.asList(5, 2, 9, 1, 3);
// 自然排序(升序)
Collections.sort(numbers);
// 輸出: [1, 2, 3, 5, 9]
// 自定義排序(降序)
numbers.sort((a, b) -> b - a);
// 輸出: [9, 5, 3, 2, 1]
// 對象排序
List<Book> books = new ArrayList<>();
books.add(new Book("Java編程", 99));
books.add(new Book("Python入門", 69));
books.sort(Comparator.comparing(Book::getPrice));

4.2 過濾與轉(zhuǎn)換

// 過濾高價水果
List<String> expensiveFruits = fruits.stream()
    .filter(fruit -> fruit.length() > 2)
    .collect(Collectors.toList());
// 水果名稱轉(zhuǎn)大寫
List<String> upperCaseFruits = fruits.stream()
    .map(String::toUpperCase)
    .collect(Collectors.toList());

4.3 數(shù)學(xué)統(tǒng)計(jì)

IntSummaryStatistics stats = numbers.stream()
    .mapToInt(Integer::intValue)
    .summaryStatistics();
System.out.println("最大值: " + stats.getMax());
System.out.println("最小值: " + stats.getMin());
System.out.println("平均值: " + stats.getAverage());
System.out.println("總數(shù): " + stats.getSum());

4.4 列表轉(zhuǎn)換

// List轉(zhuǎn)數(shù)組
String[] fruitArray = fruits.toArray(new String[0]);
// 數(shù)組轉(zhuǎn)List(不可修改)
List<String> fixedList = Arrays.asList(fruitArray);
// 數(shù)組轉(zhuǎn)List(可修改)
List<String> modifiableList = new ArrayList<>(Arrays.asList(fruitArray));

五、ArrayList 深度解析

5.1 內(nèi)部結(jié)構(gòu)

ArrayList 就像是一個智能伸縮書架

// 簡化版ArrayList實(shí)現(xiàn)
public class SimpleArrayList<E> {
    private Object[] elements; // 存儲元素的數(shù)組
    private int size;          // 當(dāng)前元素?cái)?shù)量
    public SimpleArrayList() {
        this.elements = new Object[10]; // 初始容量
    }
    public void add(E element) {
        // 當(dāng)數(shù)組滿時自動擴(kuò)容
        if (size == elements.length) {
            Object[] newArray = new Object[elements.length * 2];
            System.arraycopy(elements, 0, newArray, 0, size);
            elements = newArray;
        }
        elements[size++] = element;
    }
}

5.2 擴(kuò)容機(jī)制

5.3 性能特點(diǎn)

操作時間復(fù)雜度說明
get(index)O(1)直接通過索引訪問
add(element)O(1)平均時間復(fù)雜度
add(index, element)O(n)需要移動后續(xù)元素
remove(index)O(n)需要移動后續(xù)元素
contains(element)O(n)需要遍歷查找

六、LinkedList 深度解析

6.1 內(nèi)部結(jié)構(gòu)

LinkedList 就像是一個帶前后指針的書本鏈

// 簡化版鏈表節(jié)點(diǎn)
class Node<E> {
    E item;         // 當(dāng)前元素
    Node<E> next;   // 下一個節(jié)點(diǎn)
    Node<E> prev;   // 上一個節(jié)點(diǎn)
    Node(Node<E> prev, E element, Node<E> next) {
        this.item = element;
        this.next = next;
        this.prev = prev;
    }
}

6.2 操作原理

// 在指定位置插入元素
public void add(int index, E element) {
    // 1. 找到目標(biāo)位置的節(jié)點(diǎn)
    Node<E> target = getNode(index);
    // 2. 創(chuàng)建新節(jié)點(diǎn)
    Node<E> newNode = new Node<>(target.prev, element, target);
    // 3. 調(diào)整前后節(jié)點(diǎn)指針
    target.prev.next = newNode;
    target.prev = newNode;
}

6.3 性能對比 ArrayList

操作ArrayListLinkedList適用場景
隨機(jī)訪問?? 快 (O(1))?? 慢 (O(n))需要頻繁按索引訪問
頭部插入?? 慢 (O(n))?? 快 (O(1))需要頻繁在開頭添加
尾部插入?? 快 (O(1))?? 快 (O(1))在末尾添加
中間插入?? 慢 (O(n))?? 快 (O(1))需要頻繁在中間插入
內(nèi)存占用較少(僅需存儲元素)較多(每個元素需要額外指針)內(nèi)存敏感場景

七、實(shí)戰(zhàn)應(yīng)用案例

7.1 學(xué)生成績管理系統(tǒng)

class Student {
    private String name;
    private int score;
    // 構(gòu)造方法、getter/setter省略
}
public class GradeSystem {
    private List<Student> students = new ArrayList<>();
    // 添加學(xué)生
    public void addStudent(Student student) {
        students.add(student);
    }
    // 按分?jǐn)?shù)排序
    public void sortByScore() {
        students.sort(Comparator.comparingInt(Student::getScore).reversed());
    }
    // 查找前N名學(xué)生
    public List<Student> getTopStudents(int n) {
        return students.stream()
            .sorted(Comparator.comparingInt(Student::getScore).reversed())
            .limit(n)
            .collect(Collectors.toList());
    }
    // 統(tǒng)計(jì)分?jǐn)?shù)分布
    public Map<String, Long> getScoreDistribution() {
        return students.stream()
            .collect(Collectors.groupingBy(
                s -> {
                    int score = s.getScore();
                    if (score >= 90) return "優(yōu)秀";
                    if (score >= 80) return "良好";
                    if (score >= 60) return "及格";
                    return "不及格";
                },
                Collectors.counting()
            ));
    }
}

7.2 購物車實(shí)現(xiàn)

class CartItem {
    private String productId;
    private String name;
    private double price;
    private int quantity;
    // 構(gòu)造方法、getter/setter省略
}
public class ShoppingCart {
    private List<CartItem> items = new LinkedList<>();
    // 添加商品
    public void addItem(CartItem newItem) {
        // 檢查是否已存在
        for (CartItem item : items) {
            if (item.getProductId().equals(newItem.getProductId())) {
                item.setQuantity(item.getQuantity() + newItem.getQuantity());
                return;
            }
        }
        items.add(newItem);
    }
    // 更新數(shù)量
    public void updateQuantity(String productId, int newQuantity) {
        items.removeIf(item -> item.getProductId().equals(productId));
        if (newQuantity > 0) {
            items.add(new CartItem(productId, newQuantity));
        }
    }
    // 計(jì)算總價
    public double calculateTotal() {
        return items.stream()
            .mapToDouble(item -> item.getPrice() * item.getQuantity())
            .sum();
    }
    // 生成訂單
    public Order checkout() {
        Order order = new Order();
        order.setItems(new ArrayList<>(items));
        order.setTotal(calculateTotal());
        items.clear();
        return order;
    }
}

八、最佳實(shí)踐與性能優(yōu)化

8.1 選擇正確的 List 實(shí)現(xiàn)

場景推薦實(shí)現(xiàn)理由
讀多寫少ArrayList隨機(jī)訪問快
頻繁增刪LinkedList插入刪除快
多線程環(huán)境CopyOnWriteArrayList線程安全
固定大小列表Arrays.asList()內(nèi)存優(yōu)化
不可變列表List.of()安全簡潔

8.2 性能優(yōu)化技巧

   預(yù)分配容量(減少擴(kuò)容開銷)

// 預(yù)計(jì)存儲1000個元素
List<String> largeList = new ArrayList<>(1000);

       批量操作(減少方法調(diào)用) 

// 差: 多次調(diào)用add
for (String item : items) {
    list.add(item);
}
// 好: 批量添加
list.addAll(items);

避免在循環(huán)中調(diào)用size

// 差: 每次循環(huán)都調(diào)用size()
for (int i = 0; i < list.size(); i++) {
    // ...
}
// 好: 緩存size值
int size = list.size();
for (int i = 0; i < size; i++) {
    // ...
}

使用subList視圖

// 創(chuàng)建子列表視圖(不復(fù)制數(shù)據(jù))
List<String> sub = list.subList(0, 5);

九、常見問題與解決方案 (30分鐘)

ConcurrentModificationException

問題:遍歷時修改集合

List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
for (String s : list) {
    if ("B".equals(s)) {
        list.remove(s); // 拋出異常
    }
}

解決方案

// 1. 使用Iterator的remove方法
Iterator<String> it = list.iterator();
while (it.hasNext()) {
    String s = it.next();
    if ("B".equals(s)) {
        it.remove(); // 安全刪除
    }
}
// 2. 使用Java 8+ removeIf
list.removeIf("B"::equals);
// 3. 創(chuàng)建副本遍歷
new ArrayList<>(list).forEach(s -> {
    if ("B".equals(s)) {
        list.remove(s);
    }
});

性能陷阱:LinkedList的隨機(jī)訪問

問題

LinkedList<Integer> list = new LinkedList<>();
// 填充數(shù)據(jù)...
// 隨機(jī)訪問性能差
for (int i = 0; i < list.size(); i++) {
    Integer value = list.get(i); // O(n)操作
}

解決方案

// 1. 使用迭代器
Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
    Integer value = it.next();
}
// 2. 使用增強(qiáng)for循環(huán)
for (Integer value : list) {
    // ...
}
// 3. 轉(zhuǎn)換為ArrayList(只讀場景)
List<Integer> arrayList = new ArrayList<>(list);

對象相等性判斷

問題:自定義對象在List中的行為

解決方案

class Person {
    String name;
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return Objects.equals(name, person.name);
    }
    @Override
    public int hashCode() {
        return Objects.hash(name);
    }
}

十、總結(jié)與進(jìn)階學(xué)習(xí)

List 知識體系總結(jié)

到此這篇關(guān)于Java List 使用詳解:從入門到精通的文章就介紹到這了,更多相關(guān)Java List 使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 在Java8中使用StreamAPI的實(shí)際應(yīng)用

    在Java8中使用StreamAPI的實(shí)際應(yīng)用

    本文深入探討StreamAPI的核心概念、使用場景以及實(shí)際應(yīng)用,幫助你在日常開發(fā)中更好地利用這一強(qiáng)大特性,感興趣的朋友跟隨小編一起看看吧
    2025-09-09
  • Spring Boot配置讀取實(shí)現(xiàn)方法解析

    Spring Boot配置讀取實(shí)現(xiàn)方法解析

    這篇文章主要介紹了Spring Boot配置讀取實(shí)現(xiàn)方法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-08-08
  • Java中try catch的使用和如何拋出異常問題

    Java中try catch的使用和如何拋出異常問題

    這篇文章主要介紹了Java中try catch的使用和如何拋出異常問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • java中i18n的properties的亂碼問題及解決思路

    java中i18n的properties的亂碼問題及解決思路

    解決java后臺返回給前端的500信息亂碼問題,通過開啟IDEA的Transparent native-to-ascii conversion編碼,使讀取i18n配置文件的信息顯示正常,此方法僅供參考
    2026-05-05
  • Spring Boot application.yml配置文件示例詳解

    Spring Boot application.yml配置文件示例詳解

    本文詳細(xì)介紹了SpringBootapplication.yml配置文件的使用和配置項(xiàng),通過學(xué)習(xí)本文,您應(yīng)該已經(jīng)掌握了如何使用application.yml文件來配置SpringBoot應(yīng)用程序的不同組件,如數(shù)據(jù)源、數(shù)據(jù)庫、緩存、郵件服務(wù)等,感興趣的朋友一起看看吧
    2025-02-02
  • Java開發(fā)基礎(chǔ)日期類代碼詳解

    Java開發(fā)基礎(chǔ)日期類代碼詳解

    這篇文章主要介紹了Java開發(fā)基礎(chǔ)日期類的相關(guān)內(nèi)容,代碼通過日期工具類獲取指定月份的星期與日期對應(yīng)關(guān)系,以及獲取指定月份的所有日期與星期集合等,具有一定參考價值,需要的朋友可以了解下。
    2017-10-10
  • Java定時器Timer的源碼分析

    Java定時器Timer的源碼分析

    通過源碼分析,我們可以更深入的了解其底層原理。本文將通過Timer的源碼,帶大家深入了解Java?Timer的使用,感興趣的小伙伴可以了解一下
    2022-11-11
  • 解決IDEA 左側(cè)Project中沒有out文件夾的問題

    解決IDEA 左側(cè)Project中沒有out文件夾的問題

    這篇文章主要介紹了解決IDEA 左側(cè)Project中沒有out文件夾的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02
  • Spring實(shí)現(xiàn)動態(tài)修改時間參數(shù)并手動開啟關(guān)停操作

    Spring實(shí)現(xiàn)動態(tài)修改時間參數(shù)并手動開啟關(guān)停操作

    spring實(shí)現(xiàn)定時任務(wù)的方式有三種,分別是java自帶的timer類、spring task和quartz三種。本文只介紹spring自帶的task和第三方quartz,感興趣的朋友參考下吧
    2017-09-09
  • Hibernate使用hbm.xml配置映射關(guān)系解析

    Hibernate使用hbm.xml配置映射關(guān)系解析

    這篇文章主要介紹了Hibernate使用hbm.xml配置映射關(guān)系解析,具有一定參考價值,需要的朋友可以了解下。
    2017-11-11

最新評論

高清| 丰台区| 承德县| 林州市| 宜良县| 延长县| 甘孜| 湖南省| 南安市| 湖南省| 临安市| 沾益县| 和龙市| 蕉岭县| 石阡县| 仙桃市| 阿合奇县| 宁阳县| 临夏县| 宁远县| 巴里| 平度市| 博乐市| 满城县| 五莲县| 夹江县| 屏东市| 渑池县| 梧州市| 汨罗市| 扬州市| 乾安县| 邮箱| 肇庆市| 随州市| 灵寿县| 隆德县| 仁布县| 高青县| 阿克陶县| 赣州市|