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());
    }
}
相关推荐
wifi___1 天前
全局异常处理的原理
java·开发语言
To_OC1 天前
从一行入口代码啃透 NestJS:工厂模式、装饰器和依赖注入是怎么串起来的
后端·设计模式·nestjs
Python私教1 天前
多个项目怎么安全合并?先适配,再切换
后端·python·架构
2601_963870201 天前
【计算机毕业设计】基于Spring Boot的专科医院医疗管理系统
java·spring boot·课程设计
Bingo_BIG1 天前
Java Spring 批量修改,实体、接口、方法的定义
java·spring
画中有画1 天前
软件架构中质量属性(性能、安全、可扩展性)的权衡设计
java·运维·安全
Shaoxi Zhang1 天前
JAVA学习笔记035——对象和JSON格式
java·笔记·学习
赵丙双1 天前
CountDownLatch 源码分析
java·aqs·countdownlatch
Python私教1 天前
从表格到管理系统:别先写页面,先补齐权限、流程和审计
数据库·后端·架构
余额瞒着我当琳1 天前
C++--深拷贝三件套 + swap + 写时拷贝 + vector 扩容 + reserve
java·开发语言·c++