java常用工具类和API

java常用工具类和API

前言:本篇总结一些常用的工具类和api

1.0 StringBuilder

我们在处理字符串时,一般会使用StringBuilder,因为其提供了大量的API,并且效率要高于String

尤其是进行字符串拼接时,如果使用 String进行字符串拼接时,由于String和其他的封装类属于不可变数据类

型,所以对字符串的并不是在原有的基础上进行更改,而是不断产生新串的过程,不断的扔掉老对象,产生新的对

象,而StringBuilder 本质是一个容器,我们在进行拼接时是加在同一个对象中,所以相对String要快很多。所以

对字符串进行频繁修改时,更推荐使用StringBuilder

下面为一些基本运用

package com.example.StringBuilder;
public class MyStringBuilder {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("Hello");
        System.out.println(sb);
        sb.reverse();
        System.out.println(sb);
        System.out.println(sb.length());
        sb.toString();
        System.out.println(sb);
        
    }
}

1.1 StringBuffer

StringBuffer和StringBuilder的用法是完全相同的,不过相比于StringBuilder,StringBuffer的线程更安全

1.2 实际使用

现在有一个要求,要求我们写出一个将数组转换为[1,2,3]这种字符串格式的方法,我们利用StringBuilder来机

进行字符串拼接,并且实现该功能

package com.example.StringBuilder;
class MyArray{
    private int[] array=new int[10];
    private int size=0;
    public void add(int value){
        if(size<array.length){
            array[size]=value;
            size++;
        }
    }
    public String toString(){
        StringBuilder sb=new StringBuilder();
        sb.append("[");
        for(int i=0;i<size;i++) {
            sb.append(array[i]);
            if(i<size-1){
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }

}
public class MyStringBuilder {

    public static void main(String[] args) {
        MyArray arr=new MyArray();
        arr.add(10);
        arr.add(20);
        arr.add(30);
        System.out.println(arr);
    }
}

1.3 StringJoiner

StringJoiners是专门用来进行字符串拼接的工具类,使用该工具类可以使代码更简介。

同样是上面的代码,我们使用StringJoiner来进行简化,得到了下面的代码

package com.example.StringBuilder;

import java.util.StringJoiner;

class MyArray{
    private int[] array=new int[10];
    private int size=0;
    public void add(int value){
        if(size<array.length){
            array[size]=value;
            size++;
        }
    }
    public String toString(){
        StringJoiner sj=new StringJoiner(",","[","]");
        for(int i=0;i<size;i++){
            sj.add(String.valueOf(array[i]));
        }
        return sj.toString();
    }

}
public class MyStringBuilder {

    public static void main(String[] args) {
        MyArray arr=new MyArray();
        arr.add(10);
        arr.add(20);
        arr.add(30);
        System.out.println(arr);
    }
}

我们在创建StringJoiner方法时就已经通过其构造器指明了分隔符,开始符号,结束符号,接下来直接add对象就

自动按照该格式拼接字符串,不过需要注意的是,在StringBuilder时,我们直接传入数字是可以的,因为对于

append()方法,在StringBuilder类内部重载了append方法,对于各种类型的值加入都进行了处理,将其转化为

字符串并进行添加,因此我们直接传入数组的项是可以的,但对于StringJoiner的add方法,并没有进行重载,所

以我们只能传入字符值,因此需要使用valueOf方法将数组中的项的值转换为字符串进行添加

1.4 Math

Math工具类提供一些对数据进行操作的静态方法

abs(x)绝对值方法

ceil(x)向上取整

floor(x)向下取整

max(x,y)取x,y较大值

min(x,t) 取x,y较小值

pow(x,y) 返回x的y次方

random() 返回0.0到1.0的一个随机数,不包括1.0

1.5 Runtime

Runtime表示程序所在的运行环境,Runtime是一个单例类,用于与JVM进行交互,通过getRuntime()获得唯一

的Runtime实例,单例类指只有一个实现的类,通过类提供的静态方法获得该实现

首先我们来看exit方法,该方法用于关闭JVM虚拟机,传递状态码0代表正常结束

package com.example.StringBuilder;

public class MyStringBuilder {

    public static void main(String[] args) {
        Runtime jre=Runtime.getRuntime();
        jre.exit(0);//终止当前虚拟机,传递的是状态码
        System.out.println("Hello World");
    }
}

因为虚拟机被终止了,所以后面的Hello World并没有被输出

还有一些其他的方法

package com.example.StringBuilder;

import java.io.IOException;

public class MyStringBuilder {

    public static void main(String[] args) {
        Runtime jre = Runtime.getRuntime();
        System.out.println("处理器数量" + jre.availableProcessors());
        System.out.println("空闲内存" + jre.freeMemory() / 1024 / 1024 + "M");
        System.out.println("总内存" + jre.totalMemory() / 1024 / 1024 + "M");

        try {
            jre.exec("calc");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

需要注意的是exec用于执行电脑中的程序,可能会爆出异常,所以要进行异常处理

1.6 System

System代表当前系统,也是一个工具类

package com.example.StringBuilder;



public class MyStringBuilder {

    public static void main(String[] args) {
        //System.exit(0);//关闭虚拟机
        long time1 =System.currentTimeMillis();
        long x=0;
        for(int i=1;i<=1000000000;i++){
            x+=i;
        }
        long time2 =System.currentTimeMillis();
        System.out.println((time2-time1)/1000.0+"秒");
    }
}

我们可以用currentTimeMillis方法来统计运行的时间。

1.7 BigDecima

该工具类用于解决浮点数运算失真的问题

由于数据是以二进制存储的,所以小数部分是存在一定精度误差的,所以在进行浮点运算时会存在一定的精度误差

就比如下这个例子:

package com.example.bigdecimal;

public class BigDecimalDemo {
    public static void main(String[] args) {
        double d = 0.1;
        double b=0.2;
        System.out.println(d+b);
    }
}

输出结果为

0.30000000000000004

出现了失真,这时候就需要使用BigDecimal了

该工具类有两个构造器,一个接受浮点数

public BigDecimal(double val) 该构造器不能解决精度问题,只能解决两个浮点数进行运算后结果超过浮点

数范围的问题

public BigDecimal(String val)

这个构造器用于解决精度问题,通过字符串来解决精度问题,使用如下

package com.example.bigdecimal;

import java.math.BigDecimal;

public class BigDecimalDemo {
    public static void main(String[] args) {
        BigDecimal a = BigDecimal.valueOf(0.2);
        BigDecimal b=BigDecimal.valueOf(0.1);
        //BigDecimal b = new BigDecimal(Double.toString(0.2)); 也可也这样写,不过还需要转字符串
        BigDecimal c=a.add(b);
        double ans=c.doubleValue();
        System.out.println(ans);
    }
}

输出结果为0.3, 并没有出现失真

当我们使用除法时

package com.example.bigdecimal;

import java.math.BigDecimal;

public class BigDecimalDemo {
    public static void main(String[] args) {
        BigDecimal a = BigDecimal.valueOf(0.1);
        BigDecimal b=BigDecimal.valueOf(0.3);
        //BigDecimal b = new BigDecimal(Double.toString(0.2)); 也可也这样写,不过还需要转字符串
        BigDecimal c=a.divide(b);
        double ans=c.doubleValue();
        System.out.println(ans);
    }
}

发现怎么会报错呢?因为BigDecimal要求一个精确的结果,当前运算的结果0.3是一个无限循环小数,并不能完全

表示,所以会出现报错,想要解决这一问题,需要我们指定保留位数,和保留方式

package com.example.bigdecimal;

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

public class BigDecimalDemo {
    public static void main(String[] args) {
        BigDecimal a = BigDecimal.valueOf(0.1);
        BigDecimal b=BigDecimal.valueOf(0.3);
        //BigDecimal b = new BigDecimal(Double.toString(0.2)); 也可也这样写,不过还需要转字符串
        BigDecimal c=a.divide(b,2, RoundingMode.HALF_UP);
        double ans=c.doubleValue();
        System.out.println(ans);
    }
}

其中参数1是被除数,参数二是保留位数,参数三是保留模式,这里选择的是四舍五入

1.8 处理时间的工具类

1.8.1 LocalDate等

LocalDate 代表本地日期 年月日星期

LocalTime 代表本地时间 时分秒 纳秒

LocalDateTime 代表本地日期 时间 包含前两者的时间

package com.example.LocalTime;

import java.time.LocalDate;

public class MyLocalTime {
    public static void main(String[] args) {
        LocalDate ld= LocalDate.now();
        System.out.println(ld);
        //获得日期
        System.out.println(ld.getYear());
        //获得年份
        System.out.println(ld.getMonth());//获得的是枚举类型
        System.out.println(ld.getMonthValue());
        //获得月份
        System.out.println(ld.getDayOfMonth());
        System.out.println(ld.getDayOfYear());
        System.out.println(ld.getDayOfWeek().getValue());
        //同样返回的是枚举类型想要具体哪一条就用getValue()方法
        //获得日
    }
}

还有一些其他的日期修改操作就不在这给出了

由于LocalDate的对象是不可变对象,所以进行更改后返回的是新的对象

LocalDateTime和LocalTime的API和上面的差不多,也就不一一列举了

1.8.2 ZonedDateTime ZoneId

该两个类用于处理不同时区的时间

package com.example.LocalTime;
import java.time.Clock;
import java.time.ZonedDateTime;
import java.util.Set;
import java.time.LocalDate;
import java.time.ZoneId;

public class MyLocalTime {
    public static void main(String[] args) {
        ZoneId zoneId=ZoneId.systemDefault();//获取当前时区对象
//        Set<String> zonIds=ZoneId.getAvailableZoneIds();//获得支持的所有市区
//        for(String s:zonIds){
//            System.out.println(s);
//        }
        ZoneId zoneId1=ZoneId.of("Asia/Shanghai");//获取指定时区对象
        ZonedDateTime zdt=ZonedDateTime.now(zoneId1);//获取指定时区的时间
        //System.out.println(zdt);
        ZonedDateTime zonedDateTime =ZonedDateTime.now(Clock.systemUTC());//获取UTC时间
        System.out.println(zonedDateTime);
    }

}

1.8.3 Instant

Instant用于代表时间线上的某个时刻

通过获取Instant对象可以拿到此刻的时间,该事件由两部分组成,分别是从1970-0101 00:00:00开始到此刻的总

描述,加不够1s的总纳秒数

package com.example.LocalTime;
import java.time.*;
import java.util.Set;

public class MyLocalTime {
    public static void main(String[] args) {
        Instant now = Instant.now();
        System.out.println(now);
        System.out.println(now.getEpochSecond());//获得从utc起始时间到标注时区的总秒数
        System.out.println(now.getNano());//获得从不够1s的纳秒数
    }

}

1.8.4 DateTimeFormatter

该工具类用于格式化事件对象,我们之前得到的时间直接输出肯定是不美观的,所以用此工具类来进行格式化时间

输出

package com.example.LocalTime;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
import java.util.Set;

public class MyLocalTime {
    public static void main(String[] args) {
        DateTimeFormatter dft=  DateTimeFormatter.ofPattern("yyyy年MM日dd天HH点mm分ss秒");
        LocalDateTime ldt=LocalDateTime.now();
        System.out.println("当前时间为:"+ldt.format(dft));
    }
}

DateTimeFormatter 对象用来设置时间格式化格式,使用方法ofPattern 来指定格式,其中yyyy代表日期中的年

dd代表日期中的月HH代表日期中的天HH代表日期中的小时,mm和ss分别代表分钟和秒

除了上面的格式化时间,我们还需要解析时间

使用parse方法可以将符合时间格式的字符串解析成对应的时间容器对象。

package com.example.LocalTime;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
import java.util.Set;

public class MyLocalTime {
    public static void main(String[] args) {
        DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String str="2021-09-01 12:00:00";
        LocalDateTime ldt=LocalDateTime.parse(str,dtf);
        System.out.println(ldt);
    }

}

1.8.5 Period

Period用来计算两个LocalDate对象之间的间隔

package com.example.LocalTime;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
import java.util.Set;

public class MyLocalTime {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2025,3,18);
        LocalDate end =LocalDate.of(2025,3,24);
        Period period = Period.between(start,end);
        System.out.println("Period between start and end date is: "+period.getDays());
        System.out.println("Period between start and end date is: "+period.getMonths());
        System.out.println("Period between start and end date is: "+period.getYears());
    }

}

但这种写法只能获得两个时间点之间的年差,月差,日差,无法获得我们可能想要的小时差,分钟差,秒差,纳秒

差,这时候就需要使用别的工具类了

1.8.5 Duration

该工具类就是来解决上述问题的

package com.example.LocalTime;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
import java.util.Set;

public class MyLocalTime {
    public static void main(String[] args) {
        LocalDateTime start = LocalDateTime.of(2025,3,18,12,34,33);
        LocalDateTime end =LocalDateTime.of(2025,3,18,12,34,45);
        Duration duration = Duration.between(start,end);
        System.out.println("Duration in seconds: "+duration.getSeconds());
        System.out.println("Duration in nano seconds: "+duration.getNano());
        System.out.println("Duration in minutes: "+duration.toMinutes());
        System.out.println("Duration in hours: "+duration.toHours());
    }

}

1.8.6 应用

学习了这么多时间工具类,下面我们来学习下实现高考倒计时

package com.example.LocalTime;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
import java.util.Set;

public class MyLocalTime {
    public static void main(String[] args) {
        String date = "2025-06-07 09:30:00";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime ldt1=LocalDateTime.parse(date,formatter);
        LocalDateTime ldt2=LocalDateTime.now();
        Duration duration = Duration.between(ldt2,ldt1);
        System.out.println(duration.toDays()+"天"+duration.toHoursPart()+" 小时"+duration.toMinutesPart()+" 分钟"+duration.toSecondsPart()+" 秒");
    }

}

1.9 Arrays

Arrays是用来操作数组的工具类

package com.example.arrays;

import java.util.Arrays;
import java.util.function.IntUnaryOperator;

public class MyArrays {
    public static void main(String[] args) {
        int [] a={1,2,3,4,5};
        System.out.println(a);
        System.out.println(Arrays.toString(a));//输出数组
        int[] b=Arrays.copyOfRange(a,0,4);//复制数组
        System.out.println(Arrays.toString(b));
        int[] c=Arrays.copyOf(a,10);//对数组进行扩容并复制,不足的部分用0填充
        System.out.println(Arrays.toString(c));
        Arrays.setAll(c, new IntUnaryOperator() {
            @Override
            public int applyAsInt(int operand) {
                return operand+2;
            }
        });
        // 对数组进行更改,第一个参数是需要更改的数组,第二个参数是一个IntUnaryOperator接口的实现类,applyAsInt方法是对数组中的每一个元素进行操作,可用lambda表达式
        System.out.println(Arrays.toString(c));
    }
}

2.0 对象之间排序

对数组排序有sort方法,对以对象作为元素的数组呢?

实现对象数组的排序有两种方法

第一种是重写compareTo方法,该方法是调用Array的sort函数时所调用的比较方法

package com.example.arrays;

import java.util.Arrays;
import java.util.function.IntUnaryOperator;

public class MyArrays {
    public static void main(String[] args) {
        Student[] students = { new Student("张三", 20), new Student("李四", 22), new Student("王五", 21) };
        Arrays.sort(students);
        System.out.println(Arrays.toString(students));
    }
}
class Student implements Comparable<Student> {
    private String name;
    private int age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String toString() {
        return "[name=" + name + ", age=" + age + "]";
    }

    @Override
    public int compareTo(Student o) {
        return this.age - o.age;
    }
}

此时为升序排序,想要实现降序排序则return o.age - this.age;

还有一种方法是直接给sort函数传入排序规则,可用使用lambda表达式

package com.example.arrays;

import java.util.Arrays;
import java.util.function.IntUnaryOperator;

public class MyArrays {
    public static void main(String[] args) {
        Student[] students = { new Student("张三", 20), new Student("李四", 22), new Student("王五", 21) };
        Arrays.sort(students, (o1, o2) -> o1.getAge() - o2.getAge());
        System.out.println(Arrays.toString(students));
    }
}
class Student {
    private String name;
    private int age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public int getAge() {
        return age;
    }
    public String toString() {
        return "[name=" + name + ", age=" + age + "]";
    }
}

这种写法是升序排序,想要改变顺序同样交换即可

posted @ 2025-03-15 19:44  折翼的小鸟先生  阅读(54)  评论(0)    收藏  举报