【java笔记】No6.建议收藏!Java 常用 API 总结
·
Java 常用 API 核心总结
API(Application Programming Interface)是 Java 提供的现成类库,掌握常用 API 能大幅提升开发效率。这份笔记总结了 Java 开发中高频使用的 API,从基础到常用工具类,系统梳理了他们的核心用法和场景。
一、基础核心 API
1. Object 类(所有类的父类)
Object 是 Java 中所有类的根类,所有类都直接/间接继承它,核心方法必须掌握:
| 方法名 | 作用 |
|---|---|
equals(Object obj) |
比较两个对象是否相等(默认比较地址,子类通常重写,如 String、Integer) |
hashCode() |
返回对象的哈希值(与 equals 配套重写) |
toString() |
返回对象的字符串表示(默认返回“类名@哈希值”,子类重写后返回属性信息) |
getClass() |
返回对象的运行时类(Class 对象) |
clone() |
创建对象的副本(需实现 Cloneable 接口) |
finalize() |
垃圾回收前调用(已过时,不推荐使用) |
示例:重写 Object 方法
public class Student {
private String name;
private int age;
// 重写 toString:返回属性信息
@Override
public String toString() {
return "Student{name='" + name + "', age=" + age + "}";
}
// 重写 equals:比较属性是否相等
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
// 重写 hashCode:与 equals 配套
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
2. String 类(字符串操作)
String 是不可变字符序列(一旦创建,内容不能修改),核心方法:
(1)常用获取方法
String str = "Hello Java";
str.length(); // 获取长度:9
str.charAt(1); // 获取指定索引字符:'e'
str.indexOf("Java"); // 查找子串位置:6(不存在返回-1)
str.lastIndexOf("l"); // 从后查找子串位置:3
(2)常用判断方法
str.equals("hello java"); // 区分大小写比较:false
str.equalsIgnoreCase("hello java"); // 不区分大小写:true
str.startsWith("Hello"); // 是否以指定前缀开头:true
str.endsWith("Java"); // 是否以指定后缀结尾:true
str.isEmpty(); // 是否为空:false
(3)常用操作方法
str.substring(6); // 截取子串(从索引6到末尾):"Java"
str.substring(0, 5); // 截取子串(左闭右开):"Hello"
str.replace("Java", "World"); // 替换子串:"Hello World"
str.toUpperCase(); // 转大写:"HELLO JAVA"
str.toLowerCase(); // 转小写:"hello java"
str.trim(); // 去除首尾空格(JDK11+用 strip() 更通用)
String[] arr = str.split(" "); // 分割字符串:["Hello", "Java"]
(4)注意:不可变性
String s1 = "abc";
String s2 = s1.concat("def"); // 拼接后生成新对象,s1 仍为 "abc"
3. StringBuffer & StringBuilder(可变字符串)
用于频繁修改字符串的场景,避免创建大量临时对象:
| 特性 | StringBuffer | StringBuilder |
|---|---|---|
| 线程安全 | 安全(同步方法) | 不安全 |
| 效率 | 较低 | 较高(推荐) |
| 适用场景 | 多线程环境 | 单线程环境(常用) |
核心方法(两者用法一致)
StringBuilder sb = new StringBuilder("Hello");
sb.append(" Java"); // 追加:"Hello Java"
sb.insert(5, ","); // 插入:"Hello, Java"
sb.replace(6, 10, "World"); // 替换:"Hello, World"
sb.delete(5, 6); // 删除:"Hello World"
sb.reverse(); // 反转:"dlroW olleH"
String res = sb.toString(); // 转为 String 类型
4. 包装类(基本类型→对象)
将 8 种基本类型封装为对象,方便泛型、集合等场景使用:
| 基本类型 | 包装类 | 常用常量/方法 |
|---|---|---|
| byte | Byte | Byte.MAX_VALUE、Byte.parseByte() |
| short | Short | Short.MIN_VALUE、Short.parseShort() |
| int | Integer | Integer.parseInt()、Integer.valueOf() |
| long | Long | Long.parseLong()、Long.toHexString() |
| float | Float | Float.parseFloat() |
| double | Double | Double.parseDouble() |
| char | Character | Character.isDigit()、Character.isLetter() |
| boolean | Boolean | Boolean.parseBoolean() |
核心用法
// 1. 自动装箱(基本→包装)、自动拆箱(包装→基本)
Integer i1 = 100; // 装箱
int i2 = i1; // 拆箱
// 2. 字符串转基本类型(常用)
int num = Integer.parseInt("123"); // "123" → 123
double d = Double.parseDouble("3.14");
// 3. 基本类型转字符串
String s = String.valueOf(456); // 456 → "456"
二、集合框架 API(高频核心)
集合用于存储多个对象,替代数组,核心接口:Collection(单列)、Map(双列)。
1. Collection 接口(单列集合根接口)
(1)List 子接口(有序、可重复)
- ArrayList:底层数组,查询快、增删慢,线程不安全(常用)
- LinkedList:底层链表,增删快、查询慢,适合频繁增删
- Vector:底层数组,线程安全,效率低(几乎不用)
ArrayList 核心用法
List<String> list = new ArrayList<>();
list.add("Java"); // 添加元素
list.add("Python");
list.add(1, "C++"); // 指定索引添加
list.get(0); // 获取索引0元素:"Java"
list.remove(2); // 删除索引2元素
list.size(); // 获取长度:2
list.contains("Java"); // 是否包含:true
list.clear(); // 清空集合
(2)Set 子接口(无序、不可重复)
- HashSet:底层哈希表,无序、去重,线程不安全(常用)
- LinkedHashSet:底层哈希表+链表,有序(插入顺序)、去重
- TreeSet:底层红黑树,可排序(自然排序/自定义排序)
HashSet 核心用法
Set<Integer> set = new HashSet<>();
set.add(10);
set.add(20);
set.add(10); // 重复元素,添加失败
set.size(); // 结果:2
set.remove(20); // 删除元素
set.contains(10); // true
2. Map 接口(双列集合,Key-Value)
Key 唯一,Value 可重复,常用实现类:
- HashMap:底层哈希表,无序,线程不安全,效率高(常用)
- LinkedHashMap:底层哈希表+链表,有序(插入顺序)
- TreeMap:底层红黑树,Key 可排序
- Hashtable:线程安全,效率低,不允许 Key/Value 为 null(几乎不用)
HashMap 核心用法
Map<String, Integer> map = new HashMap<>();
map.put("Java", 90); // 添加键值对
map.put("Python", 85);
map.put("Java", 95); // Key重复,覆盖Value:90→95
map.get("Java"); // 获取Value:95
map.remove("Python"); // 删除键值对
map.containsKey("Java"); // 是否包含Key:true
map.size(); // 键值对数量:1
// 遍历Map(常用)
for (String key : map.keySet()) {
Integer value = map.get(key);
System.out.println(key + ":" + value);
}
三、日期时间 API(JDK8+ 新特性)
JDK8 重构了日期时间 API,解决旧 API(Date、Calendar)的线程不安全、设计混乱问题。
1. 核心类(java.time 包)
| 类名 | 作用 | 常用方法 |
|---|---|---|
| LocalDate | 只存日期(年-月-日) | now()、of()、plusDays()、getDayOfMonth() |
| LocalTime | 只存时间(时:分:秒) | now()、of()、plusHours()、getHour() |
| LocalDateTime | 存日期+时间 | now()、of()、format()、parse() |
| DateTimeFormatter | 日期时间格式化/解析 | ofPattern()、format()、parse() |
核心用法
// 1. 获取当前时间
LocalDateTime now = LocalDateTime.now(); // 2026-03-03T15:30:20
// 2. 自定义日期时间
LocalDateTime dt = LocalDateTime.of(2026, 3, 3, 15, 30);
// 3. 日期时间计算
LocalDateTime tomorrow = now.plusDays(1); // 加1天
LocalDateTime lastHour = now.minusHours(1); // 减1小时
// 4. 格式化(日期→字符串)
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String str = now.format(fmt); // 2026-03-03 15:30:20
// 5. 解析(字符串→日期)
LocalDateTime dt2 = LocalDateTime.parse("2026-03-03 15:30:20", fmt);
四、IO 流 API(输入输出)
用于读写文件、网络数据等,核心分为:字节流(处理所有文件)、字符流(处理文本文件)。
1. 字节流(InputStream/OutputStream)
- FileInputStream:读取文件字节
- FileOutputStream:写入文件字节
- BufferedInputStream/BufferedOutputStream:缓冲流,提升读写效率(常用)
缓冲字节流读写文件(常用)
// 读取文件
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("test.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.txt"))) {
byte[] buf = new byte[1024]; // 缓冲区
int len;
while ((len = bis.read(buf)) != -1) { // 读取数据到缓冲区
bos.write(buf, 0, len); // 写入数据
}
} catch (IOException e) {
e.printStackTrace();
}
2. 字符流(Reader/Writer)
- FileReader/FileWriter:读写文本文件
- BufferedReader/BufferedWriter:缓冲字符流,支持按行读写(常用)
BufferedReader 按行读取文本
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
String line;
while ((line = br.readLine()) != null) { // 按行读取
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
五、工具类 API(开发高频)
1. Arrays 类(数组工具)
用于数组的排序、查找、转换等操作:
int[] arr = {3, 1, 2};
Arrays.sort(arr); // 排序:[1,2,3]
int index = Arrays.binarySearch(arr, 2); // 二分查找:1
String str = Arrays.toString(arr); // 转为字符串:"[1, 2, 3]"
List<Integer> list = Arrays.asList(1,2,3); // 数组转List
2. Collections 类(集合工具)
用于集合的排序、查找、同步化等:
List<Integer> list = new ArrayList<>(Arrays.asList(3,1,2));
Collections.sort(list); // 排序:[1,2,3]
Collections.reverse(list); // 反转:[3,2,1]
Collections.max(list); // 获取最大值:3
Collections.synchronizedList(list); // 转为线程安全的List
3. Math 类(数学运算)
提供常用数学方法,所有方法都是静态的:
Math.abs(-5); // 绝对值:5
Math.round(3.6); // 四舍五入:4
Math.ceil(3.2); // 向上取整:4.0
Math.floor(3.8); // 向下取整:3.0
Math.random(); // 生成0.0~1.0随机数
Math.pow(2, 3); // 2的3次方:8.0
六、异常处理 API
处理程序运行时的错误,核心类:Throwable(根类)→ Error(系统错误,无法处理)、Exception(可处理)。
1. 核心用法
try {
// 可能抛出异常的代码
int num = Integer.parseInt("abc"); // 抛出 NumberFormatException
} catch (NumberFormatException e) {
// 捕获异常并处理
e.printStackTrace(); // 打印异常栈信息
System.out.println("输入的不是数字");
} finally {
// 无论是否异常,都会执行(常用于释放资源)
System.out.println("finally 执行");
}
2. 自定义异常
// 定义自定义异常
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
// 抛出自定义异常
public void test(int age) throws MyException {
if (age < 0) {
throw new MyException("年龄不能为负数");
}
}
七、总结
关键点回顾
- 基础 API:Object(所有类父类)、String(不可变)、StringBuilder(可变)、包装类(基本转对象)是日常开发的基础,必须熟练;
- 集合 API:ArrayList(查询)、HashMap(键值对)是高频核心,掌握增删改查和遍历;
- 工具类 API:Arrays、Collections、Math 能简化数组、集合、数学运算操作,提升效率;
- 日期 API:JDK8+ 的 LocalDateTime/DateTimeFormatter 替代旧 Date/Calendar,是主流用法。
掌握这些常用 API 能覆盖 80% 以上的 Java 开发场景,建议结合实际案例多练习,重点理解“什么时候用、怎么用”,而非死记硬背。
更多推荐



所有评论(0)