当前位置: 首页 > ops >正文

Java核心API实战:从字符串到多线程全解析

Java常用API详解与代码实践

一、字符串处理类

1. String类

// 字符串基础操作
String str = "Hello,Java!";
System.out.println(str.substring(7)); // 输出"Java!"
System.out.println(str.indexOf("Java")); // 输出7// 正则表达式匹配
String email = "test@example.com";
System.out.println(email.matches("^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$")); // true

2. StringBuilder/StringBuffer

// 字符串拼接性能优化
StringBuilder sb = new StringBuilder();
sb.append("Java").append(17).insert(0, "Version: ");
System.out.println(sb.toString()); // 输出"Version: Java17"

二、集合框架

1. List接口

// ArrayList示例
List<String> list = new ArrayList<>();
list.add("Apple");
list.add(0, "Banana");
System.out.println(list.get(1)); // 输出"Apple"// LinkedList特殊操作
LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.addFirst(10);
linkedList.pollLast();

2. Map接口

// HashMap使用
Map<String, Integer> map = new HashMap<>();
map.put("Java", 1995);
map.computeIfAbsent("Python", k -> 1991);// TreeMap排序
TreeMap<Integer, String> treeMap = new TreeMap<>(Comparator.reverseOrder());
treeMap.put(3, "Three");
treeMap.put(1, "One");
System.out.println(treeMap.firstKey()); // 输出3

三、IO流体系

1. 文件操作

// 使用NIO读取文件
Path path = Paths.get("test.txt");
try (Stream<String> lines = Files.lines(path)) {lines.filter(line -> line.contains("Java")).forEach(System.out::println);
}// 缓冲流复制文件
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"));BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {String line;while ((line = reader.readLine()) != null) {writer.write(line.toUpperCase());writer.newLine();}
}

四、日期时间API(Java 8+)

1. 基础日期操作

LocalDate today = LocalDate.now();
LocalDate nextWeek = today.plusWeeks(1);
System.out.println(today.isBefore(nextWeek)); // true// 日期格式化
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
System.out.println(today.format(formatter));

2. 时间差计算

LocalDateTime start = LocalDateTime.of(2023, 1, 1, 9, 0);
LocalDateTime end = LocalDateTime.now();Duration duration = Duration.between(start, end);
System.out.println(duration.toDays() + " days");

五、多线程编程

1. 线程基础

// 实现Runnable接口
new Thread(() -> {IntStream.range(1, 5).forEach(i -> {System.out.println("Task-" + i);try { Thread.sleep(500); } catch (InterruptedException e) {}});
}).start();

2. 线程池管理

ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(() -> System.out.println("Task1"));
executor.submit(() -> System.out.println("Task2"));
executor.shutdown();

六、异常处理机制

1. 自定义异常

class BalanceException extends Exception {public BalanceException(String message) {super(message);}
}void withdraw(double amount) throws BalanceException {if (amount > balance) {throw new BalanceException("余额不足");}// 扣款逻辑
}

七、反射机制

1. 动态调用方法

Class<?> clazz = Class.forName("com.example.User");
Object user = clazz.getDeclaredConstructor().newInstance();Method setName = clazz.getMethod("setName", String.class);
setName.invoke(user, "张三");Field ageField = clazz.getDeclaredField("age");
ageField.setAccessible(true);
ageField.set(user, 25);

最佳实践建议

  1. 集合初始化时指定容量(如new ArrayList<>(100)
  2. 使用Objects.equals()进行空安全比较
  3. IO操作始终使用try-with-resources
  4. 多线程环境使用并发集合(如ConcurrentHashMap)
  5. 时间处理优先使用Java 8+ API

通过掌握这些核心API的用法,结合具体业务场景灵活运用,可以显著提升Java开发效率与代码质量。建议通过官方文档深入了解各个类的完整方法体系。

http://www.xdnf.cn/news/7022.html

相关文章:

  • symfonos: 2靶场
  • Compose笔记(二十五)--Brush
  • 行业事件 | 中国灾害防御协会雷电灾害分会在京正式成立
  • MySQL开发规范
  • Atcoder Beginner Contest 406
  • 网络安全深度解析:21种常见网站漏洞及防御指南
  • 一文读懂----Docker 常用命令
  • SQL性能分析
  • 23种设计模式考试趋势分析之——适配器(Adapter)设计模式——求三连
  • IDE/IoT/搭建物联网(LiteOS)集成开发环境,基于 VSCode + IoT Link 插件
  • ubuntu18.04编译qt5.14.2源码
  • [特殊字符] SSL/TLS 中的密钥协商流程笔记
  • 进程的调度
  • SpringBoot快速上手
  • CUDA 纹理入门
  • replay下载
  • SOLID 面对象设计的五大基本原则
  • 一种基于条件约束注意力生成对抗网络的水下图像增强模型
  • 二叉树构造:从前序、中序与后序遍历序列入手
  • USB学习【11】STM32 USB初始化过程详解
  • 【AI】Ubuntu 22.04 4060Ti16G 基于SWIFT框架的LoRA微调 模型Qwen3-1.8B 数据集弱智吧 微调笔记
  • 【iOS】探索消息流程
  • 上位机知识篇---流式Web服务器模式的实现
  • STM32SPI通信基础及CubeMX配置
  • OVS练习笔记20250518
  • Kubernetes控制平面组件:Kubelet详解(五):切换docker运行时为containerd
  • Vue-监听属性
  • 报错System.BadImageFormatException:“试图加载格式不正确的程序。 (异常来自 HRESULT:0x8007000B)”
  • 面试中的线程题
  • 数据结构:二叉树一文详解