java实用类

发布于:2025-06-04 ⋅ 阅读:(23) ⋅ 点赞:(0)

System

System 是 Java 标准库中的一个系统类,它主要用于提供与系统相关的功能和资源访问,是 Java 程序与运行环境之间交互的重要桥梁。

System.exit(int status);

public class ExitExample {
    public static void main(String[] args) {
        System.out.println("程序开始执行");

        // 模拟正常结束
        System.exit(0);

        // 下面的代码不会被执行
        System.out.println("这行不会打印");
    }
}

currentTimeMillis

测试代码运行时间

long startTime = System.currentTimeMillis();

// 要测试的代码
for (int i = 0; i < 1000000; i++) {
    // do something
}

long endTime = System.currentTimeMillis();
long duration = endTime - startTime;

System.out.println("代码运行时间: " + duration + " 毫秒")

String 类

String两种创建方式

String代表字符串,它的对象可以封装字符串数据,并提供了很多方法完成对字符串的处理。
1、创建字符串对象,封装字符串数据
2、调用String提供的操作字符串数据的方法

方式一: Java 程序中的所有字符串文字(例如“abc”)都为此类的对象。

String name = "小黑";
String schoolName = "黑马程序员";

方式二: 调用String类的构造器初始化字符串对象。

构造器 说明
public String() 创建一个空白字符串对象,不含有任何内容
public String(String original) 根据传入的字符串内容,来创建字符串对象
public String(char[] chars) 根据字符数组的内容,来创建字符串对象
public String(byte[] bytes) 根据字节数组的内容,来创建字符串对象

两种方式的区别

  • 只要是以“…方式写出的字符串对象,会存储到字符串常量池,且相同内容的字符串只存储一份;
  • 通过new方式创建字符串对象,每new一次都会产生一个新的对象放在堆内存中。

方式一
在这里插入图片描述
方式二
在这里插入图片描述

public class ublic static void main(String[] args) {
    // 目标:掌握创建字符串对象,封装要处理的字符串数据,调用String提供的方法处理字符串。
    // 1、推荐方式一: 直接“”就可以创建字符串对象,封装字符串数据。
    String s1 = "hello,黑马";
    System.out.println(s1);
    System.out.println(s1.length()); // 处理字符串的方法。

    // 2、方式二:通过构造器初始化对象。
    String s2 = new String(); // 不推荐
    System.out.println(s2); // ""空字符串

    String s3 = new String("hello,黑马"); // 不推荐
    System.out.println(s3);

    char[] chars = {'h','e','l','l','o',',','黑','马'};
    String s4 = new String(chars);
    System.out.println(s4);

    byte[] bytes = {97, 98, 99, 65, 66, 67};
    String s5 = new String(bytes);
    System.out.println(s5);

    System.out.println("========================================");
    // 只有“”给出的字符串对象放在字符串常量池,相同内容只放一个。
    String t1 = "abc";
    String t2 = "abc";
    System.out.println(t1 == t2);// true

    String t3 = new String("abc");
    String t4 = new String("abc");
    System.out.println(t3 == t4); //false
    }
}

String提供的常用方法

方法名 说明
public int length() 获取字符串的长度返回(就是字符个数)
public char charAt(int index) 获取某个索引位置处的字符返回
public char[] toCharArray(): 将当前字符串转换成字符数组返回
public boolean equals(Object anObject) 判断当前字符串与另一个字符串的内容一样,一样返回true
public boolean equalsIgnoreCase(String anotherString) 判断当前字符串与另一个字符串的内容是否一样(忽略大小写)
public String substring(int beginIndex, int endIndex) 根据开始和结束索引进行截取,得到新的字符串(包前不包后)
public String substring(int beginIndex) 从传入的索引处截取,截取到末尾,得到新的字符串返回
public String replace(CharSequence target, CharSequence replacement) 使用新值,将字符串中的旧值替换,得到新的字符串
public boolean contains(CharSequence s) 判断字符串中是否包含了某个字符串
public boolean startsWith(String prefix) 判断字符串是否以某个字符串内容开头,开头返回true,反之
public String[] split(String regex) 把字符串按照某个字符串内容分割,并返回字符串数组回来

Runtime

作用

Runtime 类是 Java 标准库中的一个类,位于 java.lang 包中。每个 Java 应用程序都有一个 Runtime 类的单例实例,通过它可以与 Java 虚拟机(JVM)运行时环境进行交互。

演示

public class RuntimeExample {
    public static void main(String[] args) throws Exception {
        // 获取 Runtime 实例
        Runtime runtime = Runtime.getRuntime();

        // 查看内存信息
        System.out.println("Total Memory: " + runtime.totalMemory());
        System.out.println("Free Memory: " + runtime.freeMemory());

        
        try {
        	// 执行系统命令(例如打开记事本)
            Process process = runtime.exec("notepad.exe");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 添加关闭钩子
        runtime.addShutdownHook(new Thread(() -> {
            System.out.println("程序正在退出...");
        }));
    }
}

Object类

Object 类是 Java 中所有类的根类,位于 java.lang 包中。如果一个类没有显式地继承自其他类,则默认继承 Object 类。
统一接口:Java 中所有对象都继承自 Object,使得可以使用统一的方式处理所有对象。
基础功能支持:提供了一些通用方法,用于对象的基本操作,如比较、字符串表示、哈希值计算等。

常用方法

方法 描述
public String toString() 返回对象的字符串表示,通常在调试或打印时使用。建议子类重写以提供更有意义的信息
public boolean equals(Object obj) 判断当前对象是否与指定对象“相等”。默认比较的是地址,通常需要重写以实现内容比较。
public int hashCode() 返回对象的哈希码,用于哈希表(如 HashMap, HashSet)中的存储和查找。若重写 equals(),应同时重写 hashCode()。
public final Class<?> getClass() 返回运行时类的 Class 对象,不能被重写。可用于反射或类型判断。

重写 toString()

@Override
public String toString() {
    return "Person{name='" + name + "', age=" + age + "}";
}

重写 equals() 和 hashCode()

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Person)) return false;

    Person person = (Person) o;

    return age == person.age && Objects.equals(name, person.name);
}

@Override
public int hashCode() {
    int result = name != null ? name.hashCode() : 0;
    result = 31 * result + age;
    return result;
}

BigInter类

BigInter 类通常用于处理非常大的整数,超出 Java 中基本数据类型(如 int 或 long)的表示范围。以下是其主要作用:

  1. 大整数运算:支持任意精度的整数运算(加、减、乘、除等),不会因溢出而丢失精度。
  2. 高精度计算:适用于金融计算、密码学、科学计算等领域,要求精确无误差的数值处理。
  3. 不可变对象:通常设计为不可变类,每次操作返回新的 BigInter 实例,保证线程安全和数据一致性。
  4. 自定义实现:可能是用户自定义的大整数类,模拟类似 Java 标准库中的 BigInteger 类功能。

BigInter 构造方法

// 从字符串构造:
BigInter bigInt = new BigInter("12345678901234567890");
// 从基本类型构造:
BigInter bigInt = new BigInter(1234567890L);

常用方法

方法名 描述
add(BigInter val) 返回两个大整数的和:this + val
subtract(BigInter val) 返回两个大整数的差:this - val
multiply(BigInter val) 返回两个大整数的乘积:this * val
divide(BigInter val) 返回两个大整数的商:this / val
mod(BigInter val) 返回模运算结果:this % val
compareTo(BigInter val) 比较两个大整数大小,返回 -1, 0, 1
equals(Object obj) 判断是否相等
toString() 返回该大整数的字符串表示
abs() 返回绝对值
negate() 返回负数形式
pow(int exponent) 返回当前数的指数次幂

演示

BigInter a = new BigInter("100");
BigInter b = new BigInter("200");

BigInter sum = a.add(b);       // 300
BigInter diff = a.subtract(b); // -100
BigInter product = a.multiply(b); // 20000
BigInter quotient = b.divide(a);  // 2

BigDecimal类

用于解决浮点型运算时,出现结果失真的问题。

在这里插入图片描述

double a = 0.1;
double b = 0.2;
System.out.println(a + b); // 0.30000000000000004
// 为什么会失真
// 浮点数在内存中以二进制形式存储,所以浮点数在计算机中无法精确表示。

常见构造器

BigDecimal的常见构造器、常用方法

构造器 说明
public BigDecimal(double val) 注意:不推荐使用这个 将 double转换为 BigDecimal
public BigDecimal(String val) 把String转成BigDecimal

常用方法

方法名 说明
public static BigDecimal valueOf(double val) 转换一个 double成 BigDecimal
public BigDecimal add(BigDecimal b) 加法
public BigDecimal subtract(BigDecimal b) 减法
public BigDecimal multiply(BigDecimal b) 乘法
public BigDecimal divide(BigDecimal b) 除法
public BigDecimal divide (另一个BigDecimal对象,精确几位,舍入模式) 除法、可以控制精确到小数几位
public double doubleValue() 将BigDecimal转换为double

演示

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Test3 {
    public static void main(String[] args) {
        // 目标:掌握BigDecimal解决小数运算结果失真问题。
        double a = 0.1;
        double b = 0.2;
        System.out.println(a + b); // 0.30000000000000004
        // 为什么会失真
        // 浮点数在内存中以二进制形式存储,所以浮点数在计算机中无法精确表示。

        // 如何解决呢? 使用BigDecimal
        // 1、把小数包装成BigDecimal对象来运算才可以。
        // 必须使用 public BigDecimal(String val) 字符串构造器才能解决失真问题
//        BigDecimal a1 = new BigDecimal(Double.toString(a));
//        BigDecimal b1 = new BigDecimal(Double.toString(b));

        // 优化方案,可以直接调用valueOf方法,内部使用的就是public BigDecimal(String val) 字符串构造器
        BigDecimal a1 = BigDecimal.valueOf(a);
        BigDecimal b1 = BigDecimal.valueOf(b);
        BigDecimal c1 = a1.add(b1);  // 解决精度问题的手段
        double result = c1.doubleValue();  // 目的 把BigDecimal对象转成double类型
        System.out.println(result);// 0.3

        System.out.println("------------");

        BigDecimal i = BigDecimal.valueOf(0.1);
        BigDecimal j = BigDecimal.valueOf(0.3);
        // 除法
        // 默认除法运算精度 divide(BigDecimal divisor, int scale, RoundingMode roundingMode)
        // scale:精度 
        // roundingMode:舍入模式
        BigDecimal k = i.divide(j, 2, RoundingMode.HALF_UP); // 抛异常
        System.out.println(k);
    }
}

StringBuilder和StringBuffer

作用

StringBuilder 和 StringBuffer 都是 Java 中用于操作可变字符串的类,它们的用法非常相似,但关键区别在于线程安全性和性能。

相同点

相同点:
都继承自 AbstractStringBuilder
都可以进行字符串的拼接、插入、删除等操作
比 String 操作更高效(避免频繁创建新对象)

类型 线程安全 性能 适用场景
StringBuilder ❌ 非线程安全 更高(无同步开销) 单线程环境下推荐使用
StringBuffer ✅ 线程安全 较低(有同步开销) 多线程环境下推荐使用

如果你的程序是单线程,优先使用 StringBuilder,效率更高。
多个线程会同时修改同一个字符串缓冲区,则应使用 StringBuffer 以保证线程安全。

演示

// 使用 StringBuilder
StringBuilder sb = new StringBuilder();
// 添加字符串
sb.append("Hello");
sb.append(" ");
sb.append("World");
System.out.println(sb.toString()); // 输出:Hello World

// 使用 StringBuffer
StringBuffer sf = new StringBuffer();
// 添加字符串
sf.append("Java");
// 在指定位置插入字符串
sf.insert(0, "Hello ");
System.out.println(sf.toString()); // 输出:Hello Java

Math类

演示

Math.abs(-3.5); //返回3.5  
Math.max(2.5, 90.5);//返回90.5
int random = (int) (Math.random() * 10); //生成一个0-9之间的随机数

Random rand=new Random(); //创建一个Random对象
for(int i=0;i<20;i++){//随机生成20个随机整数,并显示
         int num=rand.nextInt(10);//返回下一个伪随机数,整型的   	System.out.println("第"+(i+1)+"个随机数是:"+num);
} 

和时间相关的类

Date类 旧版

JDK 8之前的方案: Date 获取此刻日期时间 老项目还有。

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class Test1 {
    public static void main(String[] args) {
        // 目标:掌握java提供的获取时间的方案。
        // JDK 8之前的方案: Date 获取此刻日期时间 老项目还有。
        Date d = new Date();
        System.out.println(d);// Tue May 13 13:25:15 CST 2025

        // 格式化:SimpleDateFormat 简单日期格式化,格式化日期对象成为我们喜欢的格式。
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss EEE a");
        String result = sdf.format(d);
        System.out.println(result); // 2025年05月13日 13:25:15 周二 下午
        
    }
}

Calendar类 旧版

方法或属性 说明
int get(int field) 返回给定日历字段的值
MONTH 指示月
DAY_OF_MONTH 指示一个月中的某天
DAY_OF_WEEK 指示一个星期中的某天
// 获取日历对象
Calendar calendar = Calendar.getInstance();
// 获取月份 0-11 代表1-12月份。
int month = calendar.get(Calendar.MONTH);
System.out.println(month + 1);
int day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(day);
// 获取星期几 星期天为1  星期一到星期六 为2-7
int week = calendar.get(Calendar.DAY_OF_WEEK);
System.out.println(week);

计算2015年4月6日是一年中的第几星期

// 计算2015年4月6日是一年中的第几星期
// 创建 Calendar 实例并设置日期为 2015年4月6日(月份从0开始)
Calendar calendar = Calendar.getInstance();
calendar.set(2015, Calendar.APRIL, 6);

// 设置符合 ISO 8601 标准:
// - 每周的第一天是星期一
// - 第一周至少包含4天才算作第一周
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.setMinimalDaysInFirstWeek(4);

// 获取该日期是一年中的第几周
int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
System.out.println("ISO标准下的周数:" + weekOfYear);// 15

格式化日期 旧版

旧版的格式化日期使用 SimpleDateFormat类

//创建日期对象
Date date = new Date();
//定制日期格式
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String now = formater.format(date);
System.out.println(now);// 2025-05-16 08:29:02

新版 日期+时间

Java 8 引入了全新的日期和时间API,解决了之前版本中存在的一些问题,提供了更简洁、易用的方式处理日期和时间。新API包含了许多新的类和方法,使得日期和时间的操作更加直观和灵活。

  1. LocalDateTime:表示日期(年、月、日、星期)和时间(时、分、秒、纳秒),但不包含时区信息。
  2. LocalDate:仅表示日期(年、月、日、星期),不包含时间和时区信息。
  3. LocalTime:仅表示时间(时、分、秒、纳秒),不包含日期和时区信息。
  4. ZonedDateTime:表示日期、时间和时区,适用于跨时区操作。
  5. Period:表示日期间隔,通常用于计算两个日期之间的差异。
  6. Duration:表示时间间隔,用于计算两个时间点之间的时长。
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class Test1 {
    public static void main(String[] args) {
        // JDK 8之后的方案: LocalDate LocalTime LocalDateTime 获取此刻日期时间 新项目推荐。
        // 获取此刻日期时间对象
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);// 2025-05-13T13:25:15.551119400
        System.out.println(now.getYear());// 2025
        // 获取当前是第几天
        System.out.println(now.getDayOfYear());// 133

        LocalDateTime now2 = now.plusSeconds(60); // 60秒后
        System.out.println(now);//  2025-05-13T13:25:15.551119400
        System.out.println(now2);// 2025-05-13T13:26:15.551119400

        // 格式化:DateTimeFormatter
        // 1、创建一个格式化对象
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss EEE a");
        // 2、格式化now对象的时间
        String result2 = dtf.format(now);
        System.out.println(result2);// 2025/05/13 13:25:15 周二 下午
    }
}
获取当前日期和时间
// 获取当前日期
LocalDate currentDate = LocalDate.now();
System.out.println("当前日期: " + currentDate);
// 获取当前时间
LocalTime currentTime = LocalTime.now();
System.out.println("当前时间: " + currentTime);
// 获取当前日期和时间
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("当前日期和时间: " + currentDateTime);
日期时间计算
// 日期加减
LocalDate futureDate = currentDate.plusDays(5);
LocalDate pastDate = currentDate.minusMonths(1);
System.out.println("未来5天后的日期: " + futureDate);
System.out.println("1个月前的日期: " + pastDate);
// 时间加减
LocalTime timePlusHours = currentTime.plusHours(2);
LocalTime timeMinusMinutes = currentTime.minusMinutes(30);
System.out.println("2小时后的时间: " + timePlusHours);
System.out.println("30分钟前的时间: " + timeMinusMinutes);
// 计算日期间隔
Period period = Period.between(LocalDate.of(2023, 1, 1), LocalDate.of(2023, 12,
31));
System.out.println("年份差异: " + period.getYears());
System.out.println("月份差异: " + period.getMonths());
System.out.println("天数差异: " + period.getDays());
时区操作
// 获取带时区的日期时间
ZonedDateTime zonedDateTime = currentDateTime.atZone(ZoneId.systemDefault());
System.out.println("带时区的日期和时间: " + zonedDateTime);
// 转换时区
ZonedDateTime zonedDateTimeUTC =
zonedDateTime.withZoneSameInstant(ZoneId.of("UTC"));
System.out.println("UTC时区的日期和时间: " + zonedDateTimeUTC);
转换到其他日期时间类型
// 转换为Date类型(如果需要与旧代码兼容)
Date oldStyleDate =
Date.from(currentDateTime.atZone(ZoneId.systemDefault()).toInstant());
System.out.println("转换为Date类型: " + oldStyleDate);
// 转换为字符串与Date的相互转换(例如,从数据库读取或写入)
String dateString =
oldStyleDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().format
(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
System.out.println("日期时间字符串: " + dateString);

格式化日期 新版

新版格式化日期使用 DateTimeFormatter类

// 创建一个DateTimeFormatter对象,指定日期时间的格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd
HH:mm:ss");
// 格式化当前日期时间
String formattedDateTime = currentDateTime.format(formatter);
System.out.println("格式化后的日期和时间: " + formattedDateTime);
// 使用预定义的格式
String isoDateTime =
currentDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
System.out.println("ISO格式的日期和时间: " + isoDateTime);

总结

  1. 在进行日期和时间操作时,注意时区的处理,特别是涉及跨时区操作时。
  2. 使用DateTimeFormatter进行日期和时间的解析与格式化时,要确保使用的模式字符串与待处理的日期时间字符串相匹配。
  3. 尽量避免使用旧版的日期和时间API(如java.util.Date和java.util.Calendar),新API更加易用且功能强大。

Collections工具类

是一个用来操作集合的工具类

方法名称 说明
public static<T> boolean addAll(collection<? super T>c, T… elements) 给集合批量添加元素
public static void shuffle(List<?> list) 打乱List集合中的元素顺序
public static<T>void sort(List<T> list 对List集合中的元素进行升序排序
public staticvoid sort(List list, Comparator<? super T> c) 对List集合中元素,按照比较器对象指定的规则进行排序

请参考我的博客Collection集合,List集合,set集合,Map集合,Stream流


网站公告

今日签到

点亮在社区的每一天
去签到