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());
    }
}
相关推荐
阿俊-全栈开发3 小时前
LikeShop 单商户SaaS商城分销模块二开:佣金计算与结算逻辑实现
java·开发语言·微服务·likeshop·likeshop开源商城·likeshop多商户
wuminyu6 小时前
C++协程实现接收端的零拷贝Buffer管理原理剖析
java·linux·c语言·jvm·c++
蜗牛互联网9 小时前
WSL Containers GA:本地AI容器的生命周期、网络与治理验收
java·网络·人工智能·后端
龙亘川9 小时前
铭记英烈守初心,数字强基促服务:亘川智城退役军人服务系统的实践与价值
java·数据库·人工智能
OxYGC9 小时前
[AI工程] Spring AI 第廿一篇:存量 REST 接口的 MCP 化改造实录——工具从哪条路径注册、参数描述怎么写、身份怎么过去
java·人工智能·spring
Zhou14113610 小时前
SpringBoot_02_自动配置原理
java·spring boot·后端
FYKJ_201010 小时前
SSM校园失物招领系统41452-计算机课程设计、毕业设计
java·vue.js·spring boot·python·mysql·typescript·spark
kv11010 小时前
Android studio国内开发有关
java·数据库·android studio
卓怡学长10 小时前
w198基于springboot始于足下健康打卡平台的设计与实现
java·spring boot·spring·intellij-idea
阿狗童鞋10 小时前
Java并发编程实战指南
java·开发语言