常用类
约 1362 字大约 5 分钟
2026-03-27
一、常用类概述
Java 标准库中提供了大量常用类,帮助我们处理字符串、数字、日期、集合、对象比较等常见问题。掌握这些类,比反复手写工具方法更重要。
本章重点掌握以下内容:
ObjectString、StringBuilder- 包装类
MathBigDecimal- 日期时间类
Arrays、Objects
二、Object 类
Object 是所有类的根父类,任何类默认都直接或间接继承它。
2.1 常用方法
toString():返回对象的字符串表示equals(Object obj):比较两个对象内容是否相等hashCode():返回对象的哈希值getClass():获取运行时类型
2.2 equals 和 ==
String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true区别:
==比较的是地址值equals()默认也是比较地址,但很多类会重写成比较内容
2.3 重写 equals 和 hashCode
当对象需要作为 HashMap 的 key 或 HashSet 元素时,应同时重写这两个方法。
import java.util.Objects;
class User {
private String id;
private String name;
public User(String id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User user)) {
return false;
}
return Objects.equals(id, user.id)
&& Objects.equals(name, user.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}三、String 类
String 表示字符串,是 Java 中最常用的类之一。
3.1 String 的特点
- 字符串内容不可变
- 字符串字面量会放入字符串常量池
- 适合表示固定文本,不适合频繁拼接
String s = "hello";
s = s + " world";上面的写法会创建新对象。
3.2 常用方法
String str = "Java Programming";
System.out.println(str.length());
System.out.println(str.charAt(0));
System.out.println(str.substring(5));
System.out.println(str.contains("Pro"));
System.out.println(str.toUpperCase());
System.out.println(str.replace("Java", "JDK"));3.3 字符串比较
String a = "hello";
String b = "Hello";
System.out.println(a.equals(b));
System.out.println(a.equalsIgnoreCase(b));建议:
- 比较字符串内容用
equals - 避免直接用
== - 为防空指针,可写成
"ok".equals(status)
四、StringBuilder 和 StringBuffer
4.1 为什么需要它们
因为 String 不可变,所以频繁拼接会产生很多中间对象,影响性能。
StringBuilder sb = new StringBuilder();
sb.append("Java");
sb.append(" ");
sb.append("基础");
System.out.println(sb.toString());4.2 二者区别
StringBuilder:线程不安全,效率高,开发中更常用StringBuffer:线程安全,效率略低
结论:
- 单线程场景优先
StringBuilder - 多线程且确实共享同一对象时再考虑
StringBuffer
五、包装类
Java 为每种基本数据类型都提供了对应的包装类:
| 基本类型 | 包装类 |
|---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
5.1 自动装箱和拆箱
Integer num = 10; // 自动装箱
int value = num; // 自动拆箱5.2 常用方法
int a = Integer.parseInt("123");
String b = Integer.toString(456);
double c = Double.parseDouble("3.14");注意:
- 包装类可以为
null - 基本类型不能为
null - 拆箱时如果包装类为
null,会抛出NullPointerException
六、Math 类
Math 提供常见数学运算方法,方法都是静态的。
System.out.println(Math.abs(-10));
System.out.println(Math.max(3, 8));
System.out.println(Math.min(3, 8));
System.out.println(Math.sqrt(16));
System.out.println(Math.pow(2, 3));
System.out.println(Math.ceil(3.2));
System.out.println(Math.floor(3.8));
System.out.println(Math.round(3.6));七、BigDecimal
7.1 为什么要用 BigDecimal
float 和 double 在进行小数运算时可能出现精度问题,因此金额计算通常使用 BigDecimal。
System.out.println(0.1 + 0.2); // 0.300000000000000047.2 正确创建方式
import java.math.BigDecimal;
BigDecimal a = new BigDecimal("0.1");
BigDecimal b = new BigDecimal("0.2");
System.out.println(a.add(b));不建议这样写:
// 不推荐
BigDecimal x = new BigDecimal(0.1);因为会把二进制浮点误差一起带进去。
7.3 常用方法
BigDecimal a = new BigDecimal("10.5");
BigDecimal b = new BigDecimal("2");
System.out.println(a.add(b));
System.out.println(a.subtract(b));
System.out.println(a.multiply(b));
System.out.println(a.divide(b));对于不能整除的除法,通常要指定保留位数和舍入方式:
BigDecimal result = a.divide(
new BigDecimal("3"),
2,
java.math.RoundingMode.HALF_UP
);八、日期时间类
8.1 旧版日期类
早期常见类有:
DateCalendarSimpleDateFormat
这些类现在仍能见到,但设计上存在可变、线程不安全等问题。
8.2 推荐使用 java.time
Java 8 之后推荐使用 java.time 包。
常用类:
LocalDate:日期LocalTime:时间LocalDateTime:日期时间DateTimeFormatter:格式化器
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
LocalDate today = LocalDate.now();
LocalDateTime now = LocalDateTime.now();
System.out.println(today);
System.out.println(now);
String text = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(text);8.3 常见操作
LocalDate date = LocalDate.of(2026, 3, 27);
System.out.println(date.plusDays(7));
System.out.println(date.minusMonths(1));
System.out.println(date.getYear());九、Arrays 类
Arrays 是操作数组的工具类。
import java.util.Arrays;
int[] arr = {3, 1, 5, 2};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
int[] copy = Arrays.copyOf(arr, 6);
System.out.println(Arrays.toString(copy));常见方法:
sort():排序toString():转字符串copyOf():复制数组binarySearch():二分查找equals():比较数组内容
十、Objects 类
Objects 常用于空值判断和重写 equals、hashCode。
import java.util.Objects;
String name = null;
System.out.println(Objects.isNull(name));
System.out.println(Objects.nonNull(name));
System.out.println(Objects.equals("a", "a"));常见方法:
equals(a, b)hash(...)isNull(obj)nonNull(obj)requireNonNull(obj)
十一、System 类
System 类也非常常用。
System.out.println("输出内容");
System.err.println("错误内容");
long now = System.currentTimeMillis();
System.out.println(now);常见用途:
- 标准输出与错误输出
- 获取当前时间戳
- 获取环境变量和系统属性
十二、常见易错点
12.1 用 == 比较字符串
这是最常见错误之一,应使用 equals()。
12.2 金额计算使用 double
这会导致精度问题,应优先使用 BigDecimal。
12.3 忘记重写 hashCode
只重写 equals 不重写 hashCode,会导致哈希集合行为异常。
12.4 拆箱空对象
Integer count = null;
// int num = count; // 会抛出空指针异常十三、实践建议
- 字符串频繁拼接时使用
StringBuilder - 金额计算统一使用
BigDecimal - 新项目优先使用
java.time - 需要对象内容比较时,规范重写
equals和hashCode - 优先使用 JDK 提供的工具类,不要重复造轮子
