Java核心类解析:String不可变性-新时间API特性-包装类使用误区

作者:袖梨 2026-06-01

掌握Java核心类库是开发者必备技能,String特性、时间处理与工具类封装尤其关键。本文将深入解析这些高频考点。

前言

在Java开发中,String不可变性、StringBuilder性能优化以及JDK8时间API是必须掌握的核心知识点,这些内容在技术面试中出现频率极高。

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


1. String:不可变与常量池

String s1 = "hello";
String s2 = new String("hello");
System.out.println(s1 == s2);      // false
System.out.println(s1.equals(s2)); // true

通过地址比较的==与内容比较的equals()结果不同,这是因为常量池会复用字面量,而new操作必定创建新对象。

2. StringBuilder vs StringBuffer

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

进行字符串拼接时务必使用StringBuilder,否则将严重影响程序性能。

3. JDK 8 新时间 API

LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

相比传统的DateCalendar,新API设计更清晰,具备不可变性和线程安全性,使用体验类似JS的dayjs库。

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

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:

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:

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());
    }
}

本文系统梳理了Java常用类的核心知识点,包括String特性、字符串处理优化、时间API使用技巧等,这些内容在实际开发和面试中都至关重要,建议开发者深入理解并灵活运用。

相关文章

精彩推荐