Java 常用类:String不可变、新时间API与包装类陷阱

前言

学常用类。String的不可变性、StringBuilder的性能优势、JDK 8新时间API,每个都是面试常考点。


1. String:不可变与常量池

java 复制代码
String s1 = "hello";
String s2 = new String("hello");
System.out.println(s1 == s2);      // false
System.out.println(s1.equals(s2)); // true

== 比较地址,equals() 比较内容。常量池复用字面量,但 new String() 一定新建对象。

2. StringBuilder vs StringBuffer

线程安全 场景
String 安全(不可变) 不修改的常量
StringBuilder 不安全 单线程拼接(推荐)
StringBuffer 安全 多线程环境

循环拼接必须用 StringBuilder,否则性能极差。

3. JDK 8 新时间 API

java 复制代码
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

比旧的 Date/Calendar 设计清晰,不可变、线程安全,类似 JS 的 dayjs。

4. 包装类陷阱:== vs equals

java 复制代码
Integer a = 200;
Integer b = 200;
System.out.println(a == b);     // false!
System.out.println(a.equals(b)); // true

Integer 缓存 -128~127,超出范围 == 比较地址,结果 false。

5. 实战:工具类封装

StringUtils.java:

java 复制代码
public class StringUtils {
    
    // 判断空字符串(null 或 空串)
    public static boolean isEmpty(String str) {
        return str == null || str.trim().length() == 0;
    }
    
    // 判断非空
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }
    
    // 隐藏手机号中间四位
    public static String hidePhone(String phone) {
        if (phone == null || phone.length() != 11) {
            return phone;
        }
        return phone.substring(0, 3) + "****" + phone.substring(7);
    }
    
    // 生成指定长度随机字符串
    public static String randomString(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        return sb.toString();
    }
    
    public static void main(String[] args) {
        System.out.println(isEmpty(""));        // true
        System.out.println(isEmpty("  "));      // true
        System.out.println(hidePhone("13812345678")); // 138****5678
        System.out.println(randomString(10));   // 随机10位字符串
    }
}

DateUtils.java:

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

public class DateUtils {
    
    private static final DateTimeFormatter DEFAULT_FORMATTER = 
        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    // 格式化当前时间
    public static String now() {
        return LocalDateTime.now().format(DEFAULT_FORMATTER);
    }
    
    // 格式化指定时间
    public static String format(LocalDateTime dateTime) {
        return dateTime.format(DEFAULT_FORMATTER);
    }
    
    // 解析字符串
    public static LocalDateTime parse(String str) {
        return LocalDateTime.parse(str, DEFAULT_FORMATTER);
    }
    
    // 获取今天日期
    public static String today() {
        return LocalDate.now().toString();
    }
    
    public static void main(String[] args) {
        System.out.println("当前时间:" + now());
        System.out.println("今天日期:" + today());
    }
}
相关推荐
极光代码工作室30 分钟前
基于SpringBoot的课程预约系统
java·springboot·web开发·后端开发
IT_陈寒1 小时前
Vite热更新失效?你可能漏了这个配置
前端·人工智能·后端
Leighteen1 小时前
`try-finally` 里的 `return`:为什么 `finally` 会悄悄改掉返回值、吞掉异常
java·开发语言
名字还没想好☜2 小时前
Go 的 time.After 在 select 循环里内存泄漏:定时器堆积原理与 timer.Reset 正确姿势
java·数据库·golang·go·goroutine
SomeB1oody2 小时前
【RustyML入门】1.0. 快速上手
开发语言·后端·机器学习·rust·教程
圆山猫2 小时前
[Virtualization](三):RISC-V H-extension 与 Guest 执行模式
android·java·risc-v
caishenzhibiao2 小时前
期货先行者主图 同花顺期货通指标
java·c语言·c#
史呆芬3 小时前
分布式事务实战:微服务跨服务数据一致性解决方案
java·后端·spring cloud