Featured image of post java常用api

java常用api

本文阅读量

常用api

Object类

Object类是Java中所有类的祖宗类,因此,java中所有类的对象都可以直接使用Object类中提供的一些方法

常用方法

1
2
3
4
5
6
7
8
public static void main(String[] args) {
  Student s1 = new Student("snailsir");
  // toString()  返回对象的字符串表示形式
  System.out.println(s1.toString());
  // equals(Object o) 判断两个对象是否相等(比较两个对象地址是否一样)
  Student s2 = new Student("snailsir");
  System.out.println(s1.equals(s2)); // false
}

toString方法实际没有任何意义,equals方法,完全可以使用==进行替换,因此这两个方法提供给我们,是为了让我们按照自己的规规则进行重写

Objects工具类

Objects是一个工具类,提供了很多操作对象的静态方法给我们使用

常用方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public static void main(String[] args) {
  Student s1 = null;
  Student s2 = new Student("snailsir");
  // equals(Object a, Object b) // 先做非空判断,再比较两个对象,因此更安全可靠,在比较两个对象时,建议使用
  System.out.println(Objects.equals(s1,s2));
  // isNull(Object obj) // 判断对象是否为null,为null返回true
  System.out.println(Objects.isNull(s1)); // true
  // nonNull(Object obj) // 判断对象是否不为null,不为null则返回true
  System.out.println(Objects.nonNull(s1)); // false
}

StringBuilder

用来操作字符串的一个api

StringBuilder代表可变字符串对象,相当于是一个容器,它里面装的字符串是可以改变的

StrinigBuilder比String更适合做字符串的修改操作,效率会更高,代码也会更简洁

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// 1、创建StringBUilder对象
// StringBuilder str = new StringBuilder(); // str = "";
StringBuilder str = new StringBuilder("snailsir"); // str2 = "snailsir";

// 2、拼接字符串
str.append(" like ").append(" money "); // 链式编程
System.out.println(str); // snailsir like money
// 3、反转内容
str.reverse();
// 4、获取长度
System.out.println(str.length());
// 5、把StringBuilder对象转换成String对象,因为开发中,我们需要的大部分都是String类型
String result = str.toString();
System.out.println(result);

StringBufferStringBuilder用法一模一样,但是StringBuffer是线程安全的,StringBuilder是线程不安全的,

StringJoiner

Jdk8开始才有的,与StringBuilder一样,也是用来操作字符串的,也可以看做是一个容器,创建后里面的内容是可变的

好处

不仅能提高字符串的操作效率,并且在某些场景下使用它操作字符串,代码更简洁

1
2
3
4
5
6
7
8
int[] arr = {23,45,64,23};

// arg1: 间隔符 arg2:开始符号 arg3: 结束符号
StringJoiner str = new StringJoiner(",","[","]");
for(int i = 0;i<arr.length;i++){
  str.add(Inter.toString(arr[i]));
}
System.out.println(str);

使用StringJoiner我们不需要判断是否是最后一个元素,简化了代码

Math

是一个工具类,里面提供的都是对数据进行操作的一些静态方法

案例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 获取参数绝对值
System.out.println(Math.abs(-12)); // 12


// 向上取整
System.out.println(Math.ceil(4.0001)); // 5.0

// 向下取整
System.out.println(Math.floor(4.999)); // 4.0

// 四舍五入
System.out.println(Math.round(3.4999)); // 3


// 获取两个int值中的较大值
System.out.println(Math.max(10,20)); // 20

// 返回a的b次幂的值
System.out.println(Math.pow(2,3)); // 2的3次方 8.0

// 返回值为double的随机值,范围为[0.0,1.0)
System.out.println(Math.random());

Runtime

代表程序所在的运营环境(jvm)

Runtime是一个单例类

案例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
Runtime jre = Runtime.getRuntime();

// 终止当前运行的虚拟机,该参数用作状态代码,按照惯例,非零状态代码表示异常终止
// jre.exit(0);// 正常退出虚拟机

// 获取虚拟机能够使用的处理器数
jre.availableProcessors();

// 返回java虚拟机中的内存总量,字节数
System.out.println(jre.totalMemory()/1024.0/1024.0+"MB");

// 返回java虚拟机中的可用内存
System.out.println(jre.freeMemory()/1024.0/1024.0+"MB");

// 启动软件
Process pro = jre.exec("QQ");
// 关闭软件
pro.destroy();

System

System代表程序所在的系统,也是一个工具类

1
2
3
4
5
6
7
8
// 退出java虚拟机
// System.exit(0);

// 统计运行时间
long time1 = System.currentTimeMillis();
// 要统计性能的程序
long time2 = System.cu();
System.out.println("运行消耗时间:"+(time2-time1)/1000.0+"s");

BigDecimal

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
double a = 0.1;
double b = 0.2;
// 1、把数据包装成BigDecimal对象
// BigDecimal a1 = new BigDecimal(a); // 不使用这个,无法解决double类型运算失真的问题。这个只能用来处理大的数据,能保证即使很大的double数据(超过double范围)也能运算,但是无法解决失真问题。
BigDecimal a1 = new BigDecimal(Double.toString(a)); // 可以解决失真问题:原理是将小数部分拆分成整数,然后在运算,最后在将运算结果拼接起来

BigDecimal b1 = new BigDecimal(Double.toString(b));

// 阿里巴巴公司更推荐我们使用valueOf方法保证浮点型数据为BigDecimal对象
// 与上面的a1,b1本质是一样的,valueOf就是对上面的方法进行的封装
BigDecimal a11 = BigDecimal.valueOf(a);
BigDecimal b11 = BigDecimal.valueOf(b);

// 2、a+b
BigDecimal res = a11.add(b11); // 对象信息在堆里面
double result = res.doubleValue(); // 基本数据在栈里面,我们在这里将数据从堆里放到栈里,这样就减少了从栈跨堆去找数据的性能浪费
System.out.println(result);

// 3、a-b
BigDecimal res = a11.substract(b11); 

// 4、a*b
BigDecimal res = a11.multiply(b11); 

// 5、a/b
BigDecimal res = a11.divide(b11); 

// 6、补充:舍入模式
BigDecimal i = BigDecimal.valueOf(0.1);
BigDecimal j = BigDecimal.valueOf(0.3);

// BigDecimal k = i.divide(j);// 报错:Non-terminating decimal expansion,因为0.1/0.3的结果是0.33333无限循环小数,并不是一个精确的结果,因此就会报错
// divide(除数,保留几位小数,舍入模式)
BigDecimal k = i.divide(j,2,RoundingMode.HALF_UP);
System.out.println(k);

日期类库

Jdk8新增的日期时间

Java.time包下的类

LocalDate

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//LocalDate: 获取本地日期对象:年月日(不可变对象)
LocalDate ld = LocalDate.now(); // 获取当前日期
System.out.println(ld); // 2019-03-12

System.out.println(ld.getYear()); // 获取当前日期的年份  2019
System.out.println(ld.getMonthValue()); // 获取当前日期的月份 3
System.out.println(ld.getDayOfMonth()); // 获取当前日期是该月份的第几天 12
System.out.println(ld.getDayOfYear()); // 获取当前日期是今年的第几天 72

System.out.println(ld.getDayOfWeek().getValue()); // 获取是周几 2


// 2、修改某个信息 withYear,withMonth,withDayOfMonth,withDayOfYear
LocalDate ld2 = ld.withYear(2018);// 修改年份
LocalDate ld3 = ld.withMonth(12);// 修改月份
System.out.println(ld2); // 2018-03-12
System.out.println(ld3); // 2019-12-12

// 3、日期 加法 plusYears,plusMonths,plusDays,plusWeeks
LocalDate ld4 = ld.plusYears(2);// 增加2年
LocalDate ld5 = ld.plusMonths(2);// 增加2年
System.out.println(ld4); // 2020-03-12
System.out.println(ld5); // 2019-05-12

// 4、日期 减法 minusYears,minusMonths,minusDays,minusWeeks
LocalDate ld6 = ld.minusYears(2);// 减去2年
LocalDate ld7 = ld.minusMonths(2);// 减去2年

// 5、获取指定日期的LocalDate对象
LocalDate ld8 = LocalDate.of(2099,12,12);
LocalDate ld9 = LocalDate.of(2099,12,12);

// 6、判断2个日期对象是否相等
System.out.println(ld8.equals(ld9)); // true
System.out.println(ld8.isAfter(ld)); // true
System.out.println(ld8.isBefore(ld)); // false

LocalTime

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//LocalTime: 获取本地时间对象:时分秒纳秒(不可变对象)
LocalTime lt = LocalTime.now(); // 获取当前时间
System.out.println(lt); // 12:16:32.29456346

//1、获取时间信息
System.out.println(lt.getHour()); // 获取当前时间的小时 12
System.out.println(lt.getMinute()); // 分钟 3
System.out.println(lt.getSecond()); // 秒
System.out.println(lt.getNano()); // 纳秒


// 2、修改某个信息 withHour,withMinute,withSecond,withNano
LocalTime lt2 = lt.withHour(21);// 修改年份
LocalTime lt3 = lt.withMinute(12);// 修改月份
System.out.println(lt2); // 
System.out.println(lt3); // 

// 3、时间 加法 plusHours,plusMinutes,plusSeconds,plusNanos
LocalTime lt4 = lt.plusHours(2);// 增加2小时
LocalTime lt5 = lt.plusMinutes(2);// 增加2分钟
System.out.println(lt4); // 
System.out.println(lt5); //

// 4、时间 减法 minusHours,minusMinutes,minusSeconds,minusNanos
LocalTime lt6 = lt.minusHours(10);// 减去10小时
LocalTime lt7 = lt.minusMinutes(10);// 减去10分钟

// 5、获取指定时间的LocalTime对象
LocalTime lt8 = LocalTime.of(12,12,12);
LocalTime lt9 = LocalTime.of(12,12,12);

// 6、判断2个时间对象是否相等
System.out.println(lt8.equals(lt9)); // true
System.out.println(lt8.isAfter(lt)); // true
System.out.println(lt8.isBefore(lt)); // false

LocalDateTime

本地日期:年月日时分秒

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//LocalDateTime: 获取本地日期和时间对象:年月日时分秒纳秒(不可变对象)
LocalDateTime ldt = LocalDateTime.now(); // 获取当前日期
System.out.println(ldt); // 2019-03-12

int year = ldt.getYear(); // 获取当前年份  2019
int month = ldt.getMonthValue(); // 月
int day = ldt.getDayOfMonth(); // 日
int dayOfYear = ldt.getDayOfYear(); // 一年第几天
int dayOfWeek = ldt.getDayOfWeek().getValue(); // 周几

int hour = ldt.getHour(); // 时
int minute = ldt.getMinute(); // 分
int second = ldt.getSecond(); // 秒
int nano = ldt.getNano(); // 纳秒


// 2、修改某个信息 withYear,withMonth,withDayOfMonth,withDayOfYear
// withHour,withMinute,withSecond,withNano
LocalDateTime ldt2 = ldt.withYear(2018);// 修改年份
LocalDateTime ldt3 = ldt.withMinute(12);// 修改分钟

// 3、加法 plusYears,plusMonths,plusDays,plusWeeks
// plusHours,plusMinutes,plusSeconds,plusNanos
LocalDateTime ldt4 = ldt.plusYears(2);// 增加2年
LocalDateTime ldt5 = ldt.plusHours(2);// 增加2小时

// 4、减法 minusYears,minusMonths,minusDays,minusWeeks
// minusHours,minusMinutes,minusSeconds,minusNanos
LocalDateTime ldt6 = ldt.minusYears(2);// 减去2年
LocalDateTime ldt7 = ldt.minusHours(2);// 减去2小时

// 5、获取指定日期的LocalDateTime对象
LocalDateTime ld8 = LocalDateTime.of(2099,12,12,12,12,12);
LocalDateTime ld9 = LocalDateTime.of(2099,12,12,12,12,12,1212);

// 6、判断2个日期对象是否相等
System.out.println(ldt8.equals(ldt9)); // true
System.out.println(ldt8.isAfter(ldt)); // true
System.out.println(ldt8.isBefore(ldt)); // false

//LocalDateTime 拆分成LocalDate和LocalTime
LocalDate ld = ldt.toLocalDate();
LocalTime lt = ldt.toLocalTime();

//LocalDate和LocalTime合并成LocalDateTime
LocalDateTime ldt10 = LocalDateTime.of(ld,lt);

ZoneId与ZonedDateTime

时区

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 1、获取系统默认的时区
ZoneId zoneId = ZoneId.systemDefault();
String name = zoneId.getId(); // 默认时区的名字 等价于 zoneId.toString();
System.out.println(name);

// 2、获取java支持的全部时区Id
Set<String> zoneIds = ZoneId.getAvailableZoneIds();
System.out.println(zoneIds);


// 3、把某个时区Id封装成ZoneId对象
ZoneId americaZid = ZoneId.of("America/New_York"); // 设置成美国时区


// 4、获取某个时区的ZonedDateTime对象
// ZonedDateTime.now(); 获取系统默认时区的ZonedDateTime对象
// ZonedDateTime与LocalDateTime功能一模一样
ZonedDateTime americaNow = ZonedDateTime.now(americaZid);

System.out.println(americaNow);


// 5、世界标准时间:很多服务器要获取世界时间
ZonedDateTime utcNow = ZonedDateTime.now(Clock.systemUTC());
System.out.println(utcNow);

Instant

做代码性能分析,或者记录用户的操作时间点,推荐Instant代替Date

1
2
3
4
5
6
7
8
// 时间线上的某个时刻/时间戳
// 创建Instant的对象,获取此刻时间信息(世界标准时间)
Instant now = Instant.now();
System.out.println(now);
// 2、获取总秒数
System.out.println(now.getEpochSecond());
//3、不够1s的纳秒数
System.out.println(now.getNano());

DateTimeFormatter

用于时间的格式化和解析(时间格式化器)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
//1、创建一个日期时间格式化器对象出来
// EEE 周几
// a 上午/下午
DateTimeFormatter dtf = DateTimeFormatter.ofPatter("yyyy-MM-dd HH:mm:ss EEE a");
//2、对时间进行格式化
LocalDateTime ldt = LocalDateTime.now();
String res = dtf.format(ldt);
System.out.println(res);
//3、格式化时间,其实还有一种方案
String res2 = ldt.format(dtf);
System.out.println(res2);
//4、解析时间:解析时间一般使用LocalDateTime提供的解析方法来解析
String dateStr = "2023-11-11 11:11:11";
// 1. 必须写一个日期格式化器与这个时间格式一模一样
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime ldt2 = LocalDateTime.parse(dateStr,dtf2);
System.out.println(ldt2);

Duration与Period

Period:用于计算两个LocalDate对象相差的年数、月数、天数

Duration: 用于计算两个时间对象相差的天数、小时数、分数、秒数、纳秒数;支持LocalTime、LocalDateTime、Instant等时间

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
LocalDate start = LocalDate.of(2021,3,15);
LocalDate end = LocalDate.of(2021,10,15);
// 创建Period对象,封装两个日期对象
Period period = Period.between(start,end);
// 通过Period对象获取两个日期对象相差的信息
System.out.println(period.getYears());// 相差年份:0
System.out.println(period.getMonths());// 相差月份:6
System.out.println(period.getDays()); // 相差天数:0




LocalDateTime start = LocalDateTime.of(2021,11,11,11,11,11);
LocalDateTime end = LocalDateTime.of(2021,11,11,11,11,11);
// 创建Duration对象
Duration duration = Duration.between(start,end);
// 通过Period对象获取两个日期对象相差的信息
System.out.println(duration.toDays());// 相差天数  0
System.out.println(duration.toHours());// 相差多少小时 0
System.out.println(duration.toMinutes()); // 相差多少分 1
System.out.println(duration.toSeconds());// 相差多少秒 61
System.out.println(duration.toMinllis());// 相差多少毫秒 61000
System.out.println(duration.toNanos()); // 相差多少纳秒

// duration.toHoursPart(); // 将小时进行取余操作,倒计时常用

Arrays

用来操作数组的一个工具类

使用案例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
int[] arr = {12,45,23,65,89};
// 返回数组内容
String result = Arrays.toString(arr);
System.out.println(result);

// 2、拷贝数组的内容到一个新的数组,并返回新数组
int[] arr2 = Arrays.copyOfRange(arr,1,3); // (源数组,int from,int to)
System.out.println(arr2);// [45,23,65]

// 3、给数组扩容
int[] arr3 = Arrays.copyOf(arr,arr.length*2); // 对数组arr扩容1倍(要扩容的数组,int 扩容到多大)
System.out.println(Arrays.toString(arr3));

// 4、修改数组中的每个数据,再存入
double[] scores = {99.5,23,78.5,93,29};
// 为每个数据+10
Arrays.setAll(scores,new IntToDoubleFuntion(){
  @Override
  public double applyAsDouble(int index){
    return scores[index] + 10;
  }
});
// 可以使用Lambda简化代码
// Arrays.setAll(scores,(int index) ->  {
//    return scores[index] + 10;
//});
System.out.println(Arrays.toString(scores));
//public static void setAll(double[] array,IntToDoubleFuntion generator){
//  Objects.requireNonNull(generator);
//  for(int i = 0; i<array.length;i++){
//    array[i] = generator.applyAsDouble(i);
//  }
//}

// 5、Arrays类提供的对数组进行排序的操作
Arrays.sort(scores);// 升序排序
System.out.println(scores);

对象排序

1
2
3
4
5
6
7
Student[] students = new Student[4];
students[0] = new Student("青鸟",21,'女',168.3);
students[1] = new Student("红薯",25,'女',172.6);
students[2] = new Student("姜泥",19,'女',165.8);
students[3] = new Student("徐凤年",23,'男',183.1);

Array.sort(students);// 报错,因为不知道按照什么去进行排序

方式1:让对象所在的类实现规则接口Comparable,重写compareTo方法,来指定比较规则

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class Student implements Comparable<Student>{
  // 指定大小规则
  @Override
  public int compareTo(Student o){
    // 比较规则:左>右 返回正整数,
    // 左<右 返回负整数
    // 左=右 0
    //if(this.age > o.age){
    //  return 1;
    //} else if (this.age < o.age){
    //  return -1;
    //}
    // return 0;
    // 代码优化
    return this.age - o.age; // 升序
 		// return o.age - this.age; // 降序
  }
}

// 完成上面步骤后,在进行排序操作就不会报错了e
Array.sort(students);

方式2:sort存在重载的方法,支持自带Comparetor比较器对象来直接指定比较规则(如果两个方式都存在,优先执行方式2的–就近原则)

1
2
3
4
5
6
7
8
// public static <T> void sort(T[] a,Comparator<? super T> c)
Arrays.sort(students,new Comparator<Student>{
  @Override
  public int compare(Student o1,Student o2){
    return o1.getAge() - o2.getAge(); // 升序
    // return Double.compare(o1.getHeight(),o2.getHeight()); // 升序
  }
})

Collections

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

使用案例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// 1、为集合批量添加数据 public static <T> boolean addAll(Collection<? super T> c,T...elements)
List<String> names = new ArrayList<>();
Collections.addAll(names,"徐凤年","红薯","青鸟","姜泥");

// 2、打乱List集合中的元素顺序 public static void shuffle(List<?> list)
Collections.shuffle(names);

// 3、对list集合中的元素进行升序排序 public static <T> void sort(List<T> list) 
List<Student> students = new ArrayList<>();
// s1
// s2
Collections.addAll(students,s1,s2,s3,s4);
// 排序方式1:让对象的类实现Comparable接口,重写compare方法,指定大小比较规则
Collections.sort(students);

//  4、public static <T> void sort(List<T> lsit,Comparator<? super T> c)
// 对list集合中元素,按照比较器对象指定的规则进行排序
// 方式2:指定Comparator比较器对象,再指定比较规则
Collections.sort(students,((o1,o2)->Double.compare(o2.getHeight(),o2.getHeight()))); // 降序
使用 Hugo 构建
主题 StackJimmy 设计