17 常用工具类

目录

  • [🛠️ 17 常用工具类](#🛠️ 17 常用工具类)
    • [📑 目录](#📑 目录)
    • [17.1 Math类](#17.1 Math类)
      • [17.1.1 常用方法](#17.1.1 常用方法)
      • [17.1.2 实际应用](#17.1.2 实际应用)
    • [17.2 Arrays类](#17.2 Arrays类)
      • [17.2.1 常用方法](#17.2.1 常用方法)
      • [17.2.2 实际应用](#17.2.2 实际应用)
      • [17.2.3 二维数组操作](#17.2.3 二维数组操作)
    • [17.3 Collections类](#17.3 Collections类)
      • [17.3.1 常用方法](#17.3.1 常用方法)
      • [17.3.2 实际应用](#17.3.2 实际应用)
    • [17.4 日期时间API概述](#17.4 日期时间API概述)
      • [旧API vs 新API](#旧API vs 新API)
    • [17.5 LocalDate/LocalTime/LocalDateTime](#17.5 LocalDate/LocalTime/LocalDateTime)
      • [17.5.1 创建日期时间对象](#17.5.1 创建日期时间对象)
      • [17.5.2 获取日期时间信息](#17.5.2 获取日期时间信息)
      • [17.5.3 日期时间修改](#17.5.3 日期时间修改)
    • [17.6 DateTimeFormatter](#17.6 DateTimeFormatter)
      • [17.6.1 格式化(日期 → 字符串)](#17.6.1 格式化(日期 → 字符串))
      • [17.6.2 解析(字符串 → 日期)](#17.6.2 解析(字符串 → 日期))
      • [17.6.3 格式化模式速查](#17.6.3 格式化模式速查)
    • [17.7 Period和Duration](#17.7 Period和Duration)
      • [17.7.1 Period(日期间隔)](#17.7.1 Period(日期间隔))
      • [17.7.2 Duration(时间间隔)](#17.7.2 Duration(时间间隔))
    • [17.8 综合案例:日期工具类](#17.8 综合案例:日期工具类)
    • [17.9 本章总结](#17.9 本章总结)
    • [💬 互动时间](#💬 互动时间)
    • [📚 参考资料](#📚 参考资料)

🛠️ 17 常用工具类

更新日期 :2026年5月

版权声明 :本文为原创内容,转载请注明出处。

系列:Java入门到精通系列 · 第二阶段 · 面向对象


📑 目录

  • [17.1 Math类](#17.1 Math类)
  • [17.2 Arrays类](#17.2 Arrays类)
  • [17.3 Collections类](#17.3 Collections类)
  • [17.4 日期时间API概述](#17.4 日期时间API概述)
  • [17.5 LocalDate/LocalTime/LocalDateTime](#17.5 LocalDate/LocalTime/LocalDateTime)
  • [17.6 DateTimeFormatter](#17.6 DateTimeFormatter)
  • [17.7 Period和Duration](#17.7 Period和Duration)
  • [17.8 综合案例:日期工具类](#17.8 综合案例:日期工具类)
  • [17.9 本章总结](#17.9 本章总结)

17.1 Math类

java.lang.Math 提供了基本数学运算的方法,所有方法都是静态的。

17.1.1 常用方法

方法 说明 示例 结果
abs(x) 绝对值 Math.abs(-10) 10
max(a,b) 最大值 Math.max(3, 7) 7
min(a,b) 最小值 Math.min(3, 7) 3
pow(a,b) a的b次方 Math.pow(2, 10) 1024.0
sqrt(x) 平方根 Math.sqrt(16) 4.0
cbrt(x) 立方根 Math.cbrt(27) 3.0
ceil(x) 向上取整 Math.ceil(3.2) 4.0
floor(x) 向下取整 Math.floor(3.8) 3.0
round(x) 四舍五入 Math.round(3.5) 4
random() 0.0~1.0随机数 Math.random() 0.xxx
PI 圆周率常量 Math.PI 3.14159...

17.1.2 实际应用

java 复制代码
public class MathDemo {
    public static void main(String[] args) {
        // 绝对值
        System.out.println(Math.abs(-99)); // 99

        // 求幂
        System.out.println(Math.pow(2, 8)); // 256.0

        // 取整
        System.out.println(Math.ceil(3.1));  // 4.0
        System.out.println(Math.floor(3.9)); // 3.0
        System.out.println(Math.round(3.5)); // 4
        System.out.println(Math.round(3.4)); // 3

        // 生成 [min, max] 范围的随机整数
        int min = 1, max = 100;
        int random = (int) (Math.random() * (max - min + 1) + min);
        System.out.println("随机数:" + random);

        // 计算两点之间的距离
        double x1 = 1, y1 = 2, x2 = 4, y2 = 6;
        double distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
        System.out.println("距离:" + distance); // 5.0
    }
}

17.2 Arrays类

java.util.Arrays 提供了数组操作的工具方法。

17.2.1 常用方法

方法 说明 示例
sort(arr) 排序(升序) Arrays.sort(arr)
sort(arr, comparator) 自定义排序 Arrays.sort(arr, (a,b)->b-a)
binarySearch(arr, key) 二分查找(需先排序) Arrays.binarySearch(arr, 5)
copyOf(arr, len) 复制数组 Arrays.copyOf(arr, 10)
copyOfRange(arr, from, to) 范围复制 Arrays.copyOfRange(arr, 2, 5)
fill(arr, val) 填充 Arrays.fill(arr, 0)
equals(a1, a2) 比较数组 Arrays.equals(a1, a2)
toString(arr) 转字符串 Arrays.toString(arr)
asList(arr) 数组转List Arrays.asList("a","b")
stream(arr) 转流 Arrays.stream(arr)

17.2.2 实际应用

java 复制代码
import java.util.Arrays;

public class ArraysDemo {
    public static void main(String[] args) {
        // 排序
        int[] nums = {5, 2, 8, 1, 9, 3};
        Arrays.sort(nums);
        System.out.println(Arrays.toString(nums)); // [1, 2, 3, 5, 8, 9]

        // 二分查找(必须先排序)
        int index = Arrays.binarySearch(nums, 5);
        System.out.println("5的索引:" + index); // 3

        // 复制数组
        int[] copy1 = Arrays.copyOf(nums, 3);
        System.out.println(Arrays.toString(copy1)); // [1, 2, 3]

        int[] copy2 = Arrays.copyOf(nums, 10);
        System.out.println(Arrays.toString(copy2)); // [1, 2, 3, 5, 8, 9, 0, 0, 0, 0]

        // 范围复制
        int[] range = Arrays.copyOfRange(nums, 1, 4);
        System.out.println(Arrays.toString(range)); // [2, 3, 5]

        // 填充
        int[] filled = new int[5];
        Arrays.fill(filled, 7);
        System.out.println(Arrays.toString(filled)); // [7, 7, 7, 7, 7]

        // 比较
        int[] a = {1, 2, 3};
        int[] b = {1, 2, 3};
        System.out.println(Arrays.equals(a, b)); // true

        // 字符串数组排序
        String[] names = {"Charlie", "Alice", "Bob", "David"};
        Arrays.sort(names);
        System.out.println(Arrays.toString(names)); // [Alice, Bob, Charlie, David]

        // 按长度排序
        Arrays.sort(names, (s1, s2) -> s1.length() - s2.length());
        System.out.println(Arrays.toString(names)); // [Bob, Alice, David, Charlie]
    }
}

17.2.3 二维数组操作

java 复制代码
int[][] matrix = {{3, 1}, {2, 4}, {1, 5}};

// 按第一个元素排序
Arrays.sort(matrix, (a, b) -> a[0] - b[0]);

for (int[] row : matrix) {
    System.out.println(Arrays.toString(row));
}
// [1, 5]
// [2, 4]
// [3, 1]

17.3 Collections类

java.util.Collections 是集合框架的工具类,提供集合操作的静态方法。

17.3.1 常用方法

方法 说明 示例
sort(list) 排序 Collections.sort(list)
sort(list, comparator) 自定义排序 Collections.sort(list, comparator)
reverse(list) 反转 Collections.reverse(list)
shuffle(list) 随机打乱 Collections.shuffle(list)
swap(list, i, j) 交换 Collections.swap(list, 0, 2)
max(collection) 最大值 Collections.max(list)
min(collection) 最小值 Collections.min(list)
frequency(collection, obj) 出现次数 Collections.frequency(list, "a")
replaceAll(list, old, new) 替换所有 Collections.replaceAll(list, 0, 1)
unmodifiableList(list) 不可修改列表 Collections.unmodifiableList(list)
synchronizedList(list) 线程安全列表 Collections.synchronizedList(list)
emptyList() 空不可变列表 Collections.emptyList()
singletonList(obj) 单元素列表 Collections.singletonList("a")
nCopies(n, obj) n个相同元素 Collections.nCopies(5, 0)

17.3.2 实际应用

java 复制代码
import java.util.*;

public class CollectionsDemo {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(Arrays.asList(5, 2, 8, 1, 9, 3, 5, 2));

        // 排序
        Collections.sort(list);
        System.out.println("排序后:" + list); // [1, 2, 2, 3, 5, 5, 8, 9]

        // 反转
        Collections.reverse(list);
        System.out.println("反转后:" + list); // [9, 8, 5, 5, 3, 2, 2, 1]

        // 最大/最小
        System.out.println("最大值:" + Collections.max(list)); // 9
        System.out.println("最小值:" + Collections.min(list)); // 1

        // 频率
        System.out.println("5出现次数:" + Collections.frequency(list, 5)); // 2

        // 随机打乱
        Collections.shuffle(list);
        System.out.println("打乱后:" + list);

        // 降序排序
        Collections.sort(list, (a, b) -> b - a);
        System.out.println("降序:" + list);

        // 不可修改列表
        List<String> immutable = Collections.unmodifiableList(Arrays.asList("A", "B", "C"));
        // immutable.add("D"); // ❌ 抛出 UnsupportedOperationException

        // 创建固定大小、相同初始值的列表
        List<Integer> zeros = new ArrayList<>(Collections.nCopies(10, 0));
        System.out.println("初始列表:" + zeros);
    }
}

17.4 日期时间API概述

旧API vs 新API

对比 旧API(java.util.Date等) 新API(java.time包)
包名 java.util.Date, Calendar java.time.*
线程安全 ✅(不可变对象)
设计 混乱、易错 清晰、合理
可变性 可变 不可变
推荐 ❌ 不推荐使用 ✅ 推荐使用

📌 JDK8之后,强烈推荐使用 java.time,旧的Date和Calendar已经过时。


17.5 LocalDate/LocalTime/LocalDateTime

17.5.1 创建日期时间对象

java 复制代码
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;

public class DateTimeDemo {
    public static void main(String[] args) {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        System.out.println("今天:" + today); // 2026-05-26

        // 获取当前时间
        LocalTime now = LocalTime.now();
        System.out.println("现在:" + now); // 17:30:45.123

        // 获取当前日期时间
        LocalDateTime dateTime = LocalDateTime.now();
        System.out.println("当前:" + dateTime); // 2026-05-26T17:30:45.123

        // 指定日期
        LocalDate birthday = LocalDate.of(2000, 6, 15);
        System.out.println("生日:" + birthday); // 2000-06-15

        // 指定时间
        LocalTime meeting = LocalTime.of(14, 30, 0);
        System.out.println("会议时间:" + meeting); // 14:30

        // 指定日期时间
        LocalDateTime event = LocalDateTime.of(2026, 12, 31, 23, 59, 59);
        System.out.println("跨年:" + event);
    }
}

17.5.2 获取日期时间信息

java 复制代码
LocalDateTime now = LocalDateTime.now();

System.out.println("年:" + now.getYear());           // 2026
System.out.println("月:" + now.getMonthValue());      // 5
System.out.println("日:" + now.getDayOfMonth());      // 26
System.out.println("时:" + now.getHour());            // 17
System.out.println("分:" + now.getMinute());          // 30
System.out.println("秒:" + now.getSecond());          // 45
System.out.println("星期:" + now.getDayOfWeek());     // TUESDAY
System.out.println("一年中第几天:" + now.getDayOfYear());
System.out.println("是否闰年:" + LocalDate.now().isLeapYear());

17.5.3 日期时间修改

所有 java.time 类都是不可变的,修改操作返回新对象。

java 复制代码
LocalDate today = LocalDate.now();

// 加减操作
LocalDate tomorrow = today.plusDays(1);
LocalDate yesterday = today.minusDays(1);
LocalDate nextMonth = today.plusMonths(1);
LocalDate lastYear = today.minusYears(1);

System.out.println("今天:" + today);
System.out.println("明天:" + tomorrow);
System.out.println("昨天:" + yesterday);

// with修改(返回新对象)
LocalDate newDate = today.withYear(2025).withMonth(1).withDayOfMonth(1);
System.out.println("修改后:" + newDate); // 2025-01-01

// 日期比较
LocalDate date1 = LocalDate.of(2026, 1, 1);
LocalDate date2 = LocalDate.of(2026, 12, 31);
System.out.println("date1在date2之前:" + date1.isBefore(date2)); // true
System.out.println("date1在date2之后:" + date1.isAfter(date2)); // false
System.out.println("是否相同:" + date1.isEqual(date2));          // false

17.6 DateTimeFormatter

17.6.1 格式化(日期 → 字符串)

java 复制代码
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

LocalDateTime now = LocalDateTime.now();

// 预定义格式
DateTimeFormatter fmt1 = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
System.out.println(now.format(fmt1)); // 2026-05-26T17:30:45

// 自定义格式
DateTimeFormatter fmt2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
System.out.println(now.format(fmt2)); // 2026年05月26日 17:30:45

DateTimeFormatter fmt3 = DateTimeFormatter.ofPattern("yyyy/MM/dd");
System.out.println(now.format(fmt3)); // 2026/05/26

DateTimeFormatter fmt4 = DateTimeFormatter.ofPattern("HH:mm:ss");
System.out.println(now.format(fmt4)); // 17:30:45

17.6.2 解析(字符串 → 日期)

java 复制代码
String str = "2026-05-26";
LocalDate date = LocalDate.parse(str);
System.out.println(date); // 2026-05-26

String str2 = "2026年05月26日 17:30:45";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(str2, fmt);
System.out.println(dateTime); // 2026-05-26T17:30:45

17.6.3 格式化模式速查

符号 含义 示例
yyyy 四位年 2026
MM 两位月 05
dd 两位日 26
HH 24小时制时 17
hh 12小时制时 05
mm 分钟 30
ss 45
SSS 毫秒 123
EEEE 星期全称 Tuesday
E 星期缩写 Tue

17.7 Period和Duration

17.7.1 Period(日期间隔)

java 复制代码
import java.time.LocalDate;
import java.time.Period;

LocalDate start = LocalDate.of(2000, 6, 15);
LocalDate end = LocalDate.now();

Period period = Period.between(start, end);
System.out.println("相差:" + period.getYears() + "年" 
    + period.getMonths() + "月" + period.getDays() + "日");

// 另一种写法
Period p = Period.of(1, 2, 15); // 1年2月15天
LocalDate future = LocalDate.now().plus(p);

17.7.2 Duration(时间间隔)

java 复制代码
import java.time.Duration;
import java.time.LocalTime;

LocalTime start = LocalTime.of(9, 0);
LocalTime end = LocalTime.of(17, 30);

Duration duration = Duration.between(start, end);
System.out.println("相差:" + duration.toHours() + "小时" 
    + (duration.toMinutes() % 60) + "分钟");

// Duration用于LocalDateTime
LocalDateTime from = LocalDateTime.of(2026, 1, 1, 0, 0);
LocalDateTime to = LocalDateTime.now();
Duration d = Duration.between(from, to);
System.out.println("今年已过去:" + d.toDays() + "天");

17.8 综合案例:日期工具类

java 复制代码
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.DayOfWeek;
import java.util.ArrayList;
import java.util.List;

public class DateUtils {
    private static final DateTimeFormatter DEFAULT_FMT = 
        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter DATE_FMT = 
        DateTimeFormatter.ofPattern("yyyy-MM-dd");

    /** 获取当前日期时间字符串 */
    public static String now() {
        return LocalDateTime.now().format(DEFAULT_FMT);
    }

    /** 获取当前日期字符串 */
    public static String today() {
        return LocalDate.now().format(DATE_FMT);
    }

    /** 字符串转LocalDate */
    public static LocalDate parseDate(String dateStr) {
        return LocalDate.parse(dateStr, DATE_FMT);
    }

    /** LocalDate转字符串 */
    public static String formatDate(LocalDate date) {
        return date.format(DATE_FMT);
    }

    /** 计算年龄 */
    public static int calculateAge(LocalDate birthday) {
        return Period.between(birthday, LocalDate.now()).getYears();
    }

    /** 计算两个日期之间的天数 */
    public static long daysBetween(LocalDate start, LocalDate end) {
        return java.time.Duration.between(start.atStartOfDay(), end.atStartOfDay()).toDays();
    }

    /** 判断是否是工作日 */
    public static boolean isWorkday(LocalDate date) {
        DayOfWeek dow = date.getDayOfWeek();
        return dow != DayOfWeek.SATURDAY && dow != DayOfWeek.SUNDAY;
    }

    /** 获取某月的所有日期 */
    public static List<LocalDate> getDaysInMonth(int year, int month) {
        List<LocalDate> days = new ArrayList<>();
        LocalDate first = LocalDate.of(year, month, 1);
        LocalDate last = first.withDayOfMonth(first.lengthOfMonth());
        
        for (LocalDate d = first; !d.isAfter(last); d = d.plusDays(1)) {
            days.add(d);
        }
        return days;
    }

    /** 判断是否是闰年 */
    public static boolean isLeapYear(int year) {
        return LocalDate.of(year, 1, 1).isLeapYear();
    }

    public static void main(String[] args) {
        System.out.println("当前时间:" + now());
        System.out.println("今天日期:" + today());

        LocalDate birthday = parseDate("2000-06-15");
        System.out.println("年龄:" + calculateAge(birthday) + "岁");

        LocalDate start = parseDate("2026-01-01");
        LocalDate end = parseDate("2026-12-31");
        System.out.println("2026年有" + daysBetween(start, end) + "天");

        System.out.println("今天是工作日:" + isWorkday(LocalDate.now()));

        System.out.println("2026年2月的天数:" + getDaysInMonth(2026, 2).size());
        System.out.println("2026是闰年:" + isLeapYear(2026));
    }
}

输出示例

复制代码
当前时间:2026-05-26 17:30:45
今天日期:2026-05-26
年龄:25岁
2026年有364天
今天是工作日:true
2026年2月的天数:28
2026是闰年:false

17.9 本章总结

知识回顾

知识点 核心内容
Math 数学运算工具类,abs/pow/sqrt/ceil/floor/round/random
Arrays 数组工具类,sort/binarySearch/copyOf/toString
Collections 集合工具类,sort/reverse/shuffle/max/min
LocalDate 日期,不可变,线程安全
LocalTime 时间
LocalDateTime 日期时间
DateTimeFormatter 格式化和解析
Period 日期间隔
Duration 时间间隔

练习题

  1. 使用Arrays对一个学生数组按成绩从高到低排序。
  2. 编写一个方法,输入一个日期字符串,返回今天距离该日期还有多少天。
  3. 使用Math生成一个长度为10的随机整数数组,然后求最大值、最小值和平均值。

💬 互动时间

  • 为什么Java8要引入新的日期时间API?旧API有什么问题?
  • Arrays.sort()的底层用的是什么排序算法?

📢 下篇预告18-面向对象综合实战------ 用所学面向对象知识设计一个完整的图书管理系统!


📚 参考资料

相关推荐
做个文艺程序员1 小时前
第07篇:K8s 安全加固指南:RBAC、NetworkPolicy、OPA——Java SaaS 多租户安全隔离深度实践
java·安全·kubernetes
NE_STOP1 小时前
Docker--搭建私有镜像中心Harbor
java
摇滚侠2 小时前
IDEA 新建 JavaWeb 项目 Tomcat 和 Servlet
java·ide·intellij-idea
码客日记2 小时前
Spring Boot 全局跨域配置与前后端联调避坑
java·spring boot·后端
兰令水2 小时前
leecodecode【回溯子集】【2026.6.4打卡-java版本】
java·开发语言·深度优先
fox_lht2 小时前
14.3.重构
开发语言·后端·rust
牛油果子哥q2 小时前
【C++ const 】全场景深度精讲:修饰规则、底层常量折叠、指针 / 引用 / 成员函数实战、易错坑点与工程代码实现
开发语言·c++
闪电悠米2 小时前
黑马点评-Redisson-02_reentrant_lock
java·spring boot·redis·分布式·缓存
云烟成雨TD2 小时前
Spring AI Alibaba 1.x 系列【67】ReactAgent SSE 流式输出
java·人工智能·spring