第 25 章:StringBuilder、包装类、Math、时间 API
学习目标
- 掌握 StringBuilder 的高效使用
- 学会包装类的工具方法
- 了解 Math 和 Random
- 掌握 Java 8 新时间 API
一、StringBuilder vs StringBuffer
| 维度 | StringBuilder | StringBuffer |
|---|---|---|
| 线程安全 | ❌ 不安全 | ✅ 安全(synchronized) |
| 性能 | 快(单线程) | 慢(同步开销) |
| 适用 | 单线程 | 多线程 |
java
// 单线程用 StringBuilder(99% 场景)
StringBuilder sb = new StringBuilder();
sb.append("Hello")
.append(" ")
.append("World");
System.out.println(sb); // Hello World二、包装类工具方法
java
// Integer
Integer.parseInt("123"); // String → int
Integer.valueOf(123); // int → Integer
Integer.toBinaryString(10); // int → 二进制字符串
Integer.MAX_VALUE; // 常量
// Long, Double, Boolean 类似
Long.parseLong("100");
Double.parseDouble("3.14");
Boolean.parseBoolean("true");三、Math 类
java
Math.abs(-5); // 5(绝对值)
Math.max(3, 5); // 5
Math.min(3, 5); // 3
Math.pow(2, 10); // 1024(2^10)
Math.sqrt(16); // 4
Math.round(3.7); // 4(四舍五入)
Math.ceil(3.2); // 4(向上取整)
Math.floor(3.8); // 3(向下取整)
Math.random(); // [0, 1) 随机数Random
java
Random r = new Random();
r.nextInt(); // 任意 int
r.nextInt(100); // [0, 100)
r.nextDouble(); // [0.0, 1.0)
r.nextLong();⚠️
Math.random()不是加密安全的,安全场景用SecureRandom。
四、Java 8 新时间 API
旧的 Date / Calendar 有线程安全和 API 难用的问题,Java 8 引入了 java.time:
java
import java.time.*;
import java.time.format.DateTimeFormatter;
// 当前时间
LocalDate today = LocalDate.now(); // 2024-08-12
LocalTime now = LocalTime.now(); // 10:30:45
LocalDateTime dateTime = LocalDateTime.now(); // 2024-08-12T10:30:45
// 指定时间
LocalDate birthday = LocalDate.of(2000, 1, 1);
// 计算
LocalDate nextWeek = today.plusDays(7);
LocalDate lastMonth = today.minusMonths(1);
// 格式化
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String str = dateTime.format(fmt); // 2024-08-12 10:30:45
// 解析
LocalDateTime parsed = LocalDateTime.parse("2024-08-12 10:30:45", fmt);时间 API 速查
| 类 | 用途 |
|---|---|
LocalDate | 日期(年-月-日) |
LocalTime | 时间(时:分:秒) |
LocalDateTime | 日期 + 时间 |
Instant | 时间戳 |
Duration | 时间段 |
Period | 年月日期间 |
ZoneId | 时区 |
五、本章小结
| 要点 | 关键 |
|---|---|
| StringBuilder | 单线程首选,链式调用 |
| StringBuffer | 多线程才用 |
| 包装类 | parseXxx / valueOf / 常量 |
| Math | 静态工具方法 |
| 时间 API | java.time 包,线程安全 |
动手练习
练习 1:基础题
用 StringBuilder 实现字符串反转(不用 String.reverse()):
java
String input = "hello";
String reversed = reverse(input); // "olleh"下一章:第 26 章:Collection 与 List →