第一部分:异常处理机制

1.1 异常体系概述

Java异常体系的顶级父类是Throwable,其下分为Error和Exception两个分支。

类别 含义 处理方式
Error 程序无法处理的系统错误(如内存溢出、栈溢出) 程序无法恢复,编译器不检查
Exception 程序可以处理的异常,捕获后可能恢复 需显式处理或声明

常见Error示例:

· StackOverflowError:递归过深导致栈耗尽
· OutOfMemoryError:堆内存不足

常见运行时异常(RuntimeException):

· NullPointerException:空指针引用
· ClassCastException:类型转换失败
· IndexOutOfBoundsException:下标越界
· NumberFormatException:数字格式错误

1.2 异常处理机制

Java的异常处理遵循“抛出-捕获”模型:

```
方法抛出异常 → 运行时系统查找合适处理器 → 执行异常处理逻辑 → 继续运行或终止
```

关键字使用:

```java
// 声明可能抛出异常
public void readFile(String path) throws IOException {
    // ...
}

// 手动抛出异常
if (id < 0) {
    throw new IllegalArgumentException("ID不能为负数");
}

// 捕获异常
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("算术异常:" + e.getMessage());
} finally {
    System.out.println("始终执行");
}
```

1.3 自定义异常与异常分类

项目开发中通常将异常分为三类:

```java
// 1. 业务异常(用户操作不规范)
public class BusinessException extends RuntimeException {
    private Integer code;
    public BusinessException(Integer code, String message) {
        super(message);
        this.code = code;
    }
}

// 2. 系统异常(可预计但无法避免)
public class SystemException extends RuntimeException {
    private Integer code;
    // 类似实现
}

// 3. 其他异常(未预期的异常)
```

统一异常处理器(Spring框架风格):

```java
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    @ExceptionHandler(BusinessException.class)
    public Result handleBusinessException(BusinessException ex) {
        return new Result(ex.getCode(), null, ex.getMessage());
    }
    
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception ex) {
        return new Result(500, null, "系统繁忙,请稍后重试");
    }
}
```

1.4 异常处理最佳实践

1. 具体明确:抛出的异常应能通过类名和message准确说明问题
2. 提早抛出:尽可能早地发现并抛出异常,便于定位
3. 延迟捕获:让掌握更多信息的作用域来处理异常
4. 性能注意:try-catch块影响JVM优化,不要用异常控制正常流程

---

第二部分:集合框架深入

2.1 List与Set对比

特性 List Set
元素顺序 有序(按插入顺序) 无序(TreeSet有序)
重复元素 允许 不允许
典型实现 ArrayList, LinkedList HashSet, TreeSet

2.2 Map体系详解

HashMap vs Hashtable vs ConcurrentHashMap:

特性 HashMap Hashtable ConcurrentHashMap
线程安全 否 是(全表锁) 是(分段/CAS锁)
效率 高 低 中高
null支持 key/value均可null 均不支持 均不支持
底层结构 数组+链表+红黑树 数组+链表 数组+链表+红黑树

HashMap JDK 1.8优化:

· 引入红黑树:当链表长度超过阈值(8)时转换为红黑树,查找从O(n)优化到O(log n)
· 扩容机制的优化

ConcurrentHashMap 1.8实现:

· 使用CAS + synchronized实现细粒度锁
· 仅锁定链表或红黑树的首节点
· 并发度远优于Hashtable

2.3 Tree排序机制

TreeSet和TreeMap支持两种排序方式:

· 自然排序:元素类实现Comparable接口
· 定制排序:构造时传入Comparator对象

---

第三部分:多线程编程

3.1 线程实现方式

```java
// 方式1:继承Thread类
class MyThread extends Thread {
    public void run() {
        System.out.println("线程运行中");
    }
}

// 方式2:实现Runnable接口(推荐)
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("线程运行中");
    }
}

// 方式3:实现Callable接口(可返回结果)
FutureTask<String> task = new FutureTask<>(() -> "结果");
new Thread(task).start();
```

3.2 线程状态与生命周期

```
新建(New) → 就绪(Runnable) → 运行(Running) → 阻塞(Blocked) → 终止(Terminated)
                    ↑              ↓
                    └── 等待(Waiting) ──┘
```

3.3 线程同步与死锁

synchronized使用:

```java
// 同步实例方法
public synchronized void method1() { }

// 同步静态方法(锁Class对象)
public static synchronized void method2() { }

// 同步代码块
synchronized(lockObject) {
    // 临界区代码
}
```

避免死锁的常见策略:

· 避免嵌套锁
· 设置锁超时
· 使用ReentrantLock.tryLock()

3.4 生产者-消费者模型

经典实现需要配合wait()、notify()/notifyAll()方法,或使用BlockingQueue简化实现。

---

第四部分:输入输出流

4.1 流分类

分类维度 类型 代表类
方向 输入/输出 InputStream, OutputStream
单位 字节/字符 InputStream, Reader
功能 节点/处理 FileInputStream, BufferedInputStream

4.2 常用文件操作

```java
// 文本文件读取(字符流)
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
}

// 二进制文件读取(字节流)
try (FileInputStream fis = new FileInputStream("data.bin")) {
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = fis.read(buffer)) != -1) {
        // 处理数据
    }
}
```

4.3 对象序列化

```java
// 实现Serializable接口
class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private transient String password; // transient字段不序列化
}

// 序列化与反序列化
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user.ser"));
oos.writeObject(user);

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user.ser"));
User user2 = (User) ois.readObject();
```

4.4 Scanner解析文件

```java
try (Scanner scanner = new Scanner(new File("data.txt"))) {
    scanner.useDelimiter(",");  // 设置分隔符
    while (scanner.hasNext()) {
        String token = scanner.next();
    }
}
```

---

第五部分:JDBC数据库编程

5.1 JDBC核心步骤

```java
// 1. 加载驱动(JDBC 4.0后自动加载)
Class.forName("com.mysql.cj.jdbc.Driver");

// 2. 获取连接
String url = "jdbc:mysql://localhost:3306/mydb";
Connection conn = DriverManager.getConnection(url, "user", "password");

// 3. 创建Statement
Statement stmt = conn.createStatement();

// 4. 执行查询
ResultSet rs = stmt.executeQuery("SELECT * FROM users");

// 5. 处理结果
while (rs.next()) {
    String name = rs.getString("name");
}

// 6. 关闭资源
rs.close(); stmt.close(); conn.close();
```

5.2 PreparedStatement(预编译)

```java
String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "张三");
pstmt.setInt(2, 25);
pstmt.executeUpdate();
```

优势:防SQL注入、提高性能(预编译+可复用)

5.3 事务处理

```java
conn.setAutoCommit(false);  // 开启事务
try {
    // 执行多个SQL操作
    pstmt1.executeUpdate();
    pstmt2.executeUpdate();
    conn.commit();           // 提交
} catch (SQLException e) {
    conn.rollback();         // 回滚
}
```

---

第六部分:Lambda与函数式编程

6.1 Lambda表达式基础

```java
// 传统匿名内部类
Runnable r1 = new Runnable() {
    public void run() {
        System.out.println("Hello");
    }
};

// Lambda表达式
Runnable r2 = () -> System.out.println("Hello");
```

6.2 函数式接口

接口 参数 返回值
Predicate<T> T boolean
Consumer<T> T void
Function<T,R> T R
Supplier<T> 无 T

6.3 Stream API

```java
List<String> list = Arrays.asList("a", "bb", "ccc");

// 链式操作
list.stream()
    .filter(s -> s.length() > 1)      // 过滤
    .map(String::toUpperCase)          // 转换
    .forEach(System.out::println);     // 输出
```

---

第七部分:设计模式入门

7.1 面向对象设计原则

原则 说明
单一职责 一个类只有一个引起变化的原因
开闭原则 对扩展开放,对修改关闭
里氏替换 子类型必须能替换父类型
接口隔离 不应强迫实现不需要的方法
依赖倒置 依赖抽象而非具体实现

7.2 工厂模式

```java
interface Product { void doSomething(); }

class Factory {
    public static Product createProduct(String type) {
        if ("A".equals(type)) return new ProductA();
        if ("B".equals(type)) return new ProductB();
        throw new IllegalArgumentException();
    }
}
```

7.3 单例模式

```java
public class Singleton {
    private static volatile Singleton instance;
    private Singleton() {}
    
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
```

---

附录:知识点速查表

模块 核心要点 常见面试题
异常 try-catch-finally, throw/throws, 自定义异常 Error和Exception区别?
集合 ArrayList vs LinkedList, HashMap原理 HashMap 1.7/1.8区别?
多线程 实现方式、synchronized、volatile 如何避免死锁?
IO流 字节/字符流、序列化 transient作用?
JDBC PreparedStatement、事务 防SQL注入方法?
Lambda 函数式接口、Stream Lambda底层原理?

更多推荐