# 可变字符串类和日期相关类

# 1. 可变字符串类 (重点)

[TOC]

# <font size = 4>1.2 基本概念 </font>
  • 由于 String 类描述的字符串内容是个常量不可改变,当需要在 java 代码中描述大量类似的字符串时,只能单独申请和存储,此时会造成内存空间的浪费
  • 为了解决上述问题,可以使用 java.lang.StringBuiler 类和 java.lang.StringBuffer 类来描述字符序列可以改变的字符串,如:"ab"
  • StringBuffer 类是从 JDK1.0 开始存在,属于线程安全的类,因此效率比较低
  • StringBuilder 类是 JDK1.5 开始存在,属于非线程安全的类,效率比较高
# <font size = 4>1.2.1StringBuilder 类常用的构造方法 </font>
方法声明功能介绍
StringBuilder()使用无参方式构造对象,容量为 16
StringBuilder(int capacity)根据参数指定的容量来构造对象,容量为参数指定大小
StringBuilder(String str)根据参数指定的字符串来构造对象,容量为 16 + 字符串长度
# <font size = 4>1.2.2StringBuilder 类常用的成员方法 </font>
方法声明功能介绍
int capacity()用于返回调用对象的容量
int length()用于返回字符串的长度
StringBuilder insert(int offset,String str)插入字符串并返回调用对象的引用,就是自己
StringBuilder append(String str)追加字符串
StringBuilder deleteCharAt(int index)将当前字符串中下标为 index 位置的单个字符串删除
StringBuilder delete(int start,int end)删除字符串
StringBuilder replace(int start,int end,String str)替换字符串
StringBuilder reverse()字符串反转
  • 注意:

    ​ 作为参数传递的话,方法内部 String 不会改变其值,StringBuffer 和 StringBuilder

# 1.2.3 返回值的设计
  • StringBuilder 的很多方法的返回值均为 StringBuilder 类型,这些方法的返回语句均为:return this.

  • 由此可见,这些方法在 StringBuilder 所封装的字符序列进行改变后又返回了该对象的引用,基于这样设计的目的在于可以连续调用.

    image-20220902161550972

StringBuilder builder = new StringBuilder();
System.out.println(builder.capacity());
System.out.println(builder.length());
System.out.println("---------------------------------");
StringBuilder builder1 = new StringBuilder(10);
System.out.println(builder1.capacity());
System.out.println(builder1.length());
System.out.println("---------------------------------");
StringBuilder builder2 = new StringBuilder("hello");
// 获取 StringBuilder 容量大小的长度 16+5 => 21
System.out.println(builder2.capacity());
// 获取字符串实际长度
System.out.println(builder2.length());
  • StringBuffer,StringBuilder 是可变的下面代码用例即可体验:
System.out.println("---------------builder-------------");
StringBuilder builder = new StringBuilder("hello");
StringBuilder sb = builder.insert(0,"abc");
System.out.println("sb ="+sb);//"abchello"
System.out.println("builder ="+builder);//"abchello" 因为它返回的就是本身所以调用自己也就同样的被操作过的值
StringBuilder sb1 = builder.append("java");
System.out.println("sb1 ="+sb1);
System.out.println("builder ="+builder);
System.out.println("---------------buffer------------------");
//StringBuffer 也是一样的它们调用方法修改时返回的是本身
StringBuffer buffer = new StringBuffer("hello");
StringBuffer f = buffer.insert(0,"abc");
System.out.println("f ="+f);
System.out.println("buffer ="+buffer);
StringBuffer f1 = buffer.append("java");
System.out.println("f1"+f1);
System.out.println("buffer ="+buffer);
  • deleteCharAt 代码演示:
StringBuilder ar = new StringBuilder("helloworld");
// 此时的循环已经不代表下标,可以根据要删除字符的个数来设定比如留下 h 从 1 开始删除到 ld 的 l 前就停止打印结果为:hld
for(int i = 0;i < 7;i ++){
    // 打印结果 elwrd, 这是为什么呢?因为每删掉一位之后字符就会往前补位
    // 因此下标会发生变化
    // ar.deleteCharAt(i);
    // 解决办法让它始终只删除一个位置
    ar.deleteCharAt(1);// 打印结果 hld
}
System.out.println(ar);// 打印结果 elwrd
  • delete 代码演示:
StringBuilder ar = new StringBuilder("helloworld");
ar.delete(0,5);//java 中都有这一特定就是包含 0 但不包含 4
// 笔试考点
// 考点一:既然 StringBuilder 类的对象本身可以修改,那么为什么成员方法有返回值呢?
// 解析为了连续调用
ar.reverse().append("1").append("2").insert(0,"3").delete(0,1).reverse();
// 考点二:如何实现 StringBuilder 类型和 String 类型之间的转换呢?
String t = ar.toString();// 转换为 String
StringBuilder builder = new StringBuilder(t);// 转换为 StringBuilder
// 考点三:String,StringBuffer,StringBuilder 之间效率谁高?排列如何?
//String < StringBuffer < StringBuilder

# 2.java8 之前的日期相关类 (熟悉)

# <font size = 4>2.1 System 类的概述 </font>
  • java.lang.System 类中提供了一些有用的类字段和方法
# (2) 常用的方法
方法声明功能介绍
static long currentTimeMillis()返回当前与 1970 年 1 月 1 日 0 时 0 分 0 秒之间以毫秒为单位的时间差
# <font size = 4>2.2 Date 类的概述 </font>
# (1) 基本概念
  • java.util.Date 类主要用于描述特定的瞬间,也就是年月日时分秒,可以精确到毫秒
# (2) 常用的方法
方法声明功能介绍
Date()使用无参的方式构造对象,也就是当前系统日期
Date(long date)根据参数指定毫秒数构造对象,参数为距离 1970 年 1 月 1 日 0 时 0 分 0 秒的毫秒数
long getTime()获取调用对象距离 1970 年 1 月 1 日 0 时 0 分 0 秒的毫秒数
void setTime(long time)设置调用对象为距离基准时间 time 毫秒的时间点
Date date = new Date();// 获取当前系统时间戳
System.out.println(date);//2022 年 8 月 31 日星期三 10:02:56 CST
Date date1 = new Date(1000);//1970 年 1 月 1 日 0 时 0 分 0 秒,过去一秒的时间 1000 毫秒为 1 秒
System.out.println(date1);//1970 年 1 月 1 日星期四 08:00:01 CST
System.out.println("--------------------------------------------------------------");
long x = date1.getTime();// 获取 date1 对象构造器中的毫秒值
System.out.println(x);//1000
date1.setTime(2000);// 设置 date1 距离 1970 年 1 月 1 日 0 时 0 分 0 秒,过去二秒的时间 2000 毫秒为 2 秒
System.out.println(date1);//1970 年 1 月 1 日星期四 08:00:02 CST
# <font size = 4>2.3 SimpleDateFormat 类的概述 </font>
# (1) 基本概念
  • java.text.simpleDateFormat 类主要用于实现日期和文件之间的转换
# (2) 常用的方法
方法声明功能介绍
SimpleDateFormat()使用无参方式构造对象
SimpleDateFormat(String pattern)根据参数指定的模式来构造对象,模式主要有 y 年 M 月 d 日 H 时 m 分 s 秒
final static format(Date date)用于将日期类型转换为文本类型
Date parse(String source)用于将文件类型转换为日期类型
// 自定义格式化对象                                  y 四个因为年就是四位的嘛
SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-ddEH:mm:ss");
String format = simple.format(date);//2022 年 8 月 31 日星期三 10:35:24 CST
// 格式化日期时间
System.out.println(format);//2022-08-31 周三 10:35:24
String ar = "2022-08-31周三10:34:59";
// 解析字符串日期时间
Date d = simple.parse(ar);
System.out.println(d);//2022 年 8 月 31 日星期三 10:34:59 CST
# <font size = 4>2.4 Calendar 类的概述 (日历字段类)</font>
# (1) 基本概念
  • java.util.Calendar 类主要用于描述特定的瞬间,取代 Date 类中的过时方法实现全球化

  • 该类是个抽象类,因此不能实例化对象,其具体子类针对不同国家的日历系统,其中应用最广泛的是 GregorianCalendar (格里高利历), 对应时间上绝大多数国家 / 地区使用的标准日历系统

# (2) 常用的方法
方法声明功能介绍
static Calendar getinstance()用于获取 Calendar 类型的引用
void set(int year,int month,int date,int hourOfDay,int munute,int second)用于设置年月日时分秒信息
Date getTime()用于将 Calendar 类型转换为 Date 类型
void set(int field,int value)设置指定字段的数值
void add(int field,int amount)向指定字段增加数值
int get(Calendar.YEAR)返回字段的值
SimpleDateFormat simple = new SimpleDateFormat();
// 通过调用静态方法 instance 方法获取 Calendar 对象 定义:设置日历字段
Calendar calendar = Calendar.getInstance();
// 设置制定的日历字段的值
calendar.set(2018,12 - 1,19,0,0,0);
// 获取 Date 类型的日历字段的值
Date dr = calendar.getTime();
System.out.println("dr ="+dr);////2018 年 12 月 19 日星期三 00:00:00 CST
// 将 Date 日历字段对象格式化为字符串类型日期时间
String x = simple.format(dr);
System.out.println("String ="+x);//2018/12/19 上午 12:00
// 将字符串类型的日历字段的值解析为 Date 类型的日期时间
String z = "2018/12/19 上午12:00";
Date xx = simple.parse(z);
System.out.println("Date ="+xx);//2018 年 12 月 19 日星期三 00:00:00 CST

(3) 多态的使用场合

  • 通过方法的参数传递形成多态:

    public static void draw(Shape s){

    s.show()

    }

    draw(new Rect(1,2,3,4))

  • 在方法中直接使用多态的语法格式:

    Account acc = new FixedAccount();

  • 通过方法的返回值类型形成多态:

    Calendar getinstance(){

    return new GregorianCalendar(zone,aLocale);

    }

# 3.java8 中的日期相关类 (熟悉)

# <font size = 4>3.1 java8 日期类的由来 </font>

JDK1.0 中包含了一个 java.util.Date 类,但是它的大多数方法已经在 JDK1.1 引入 Calendar 类之后被弃用了,而 Calendar 并不比 Date 好多少,它们面临的问题是:

  • Date 类中的年份是从 1900 开始的,而月份都从 0 开始
  • 格式化只对 Date 类有用,对 Calendar 类则不能使用
  • 非线程安全等
# <font size = 4>3.2 LocalDate 类的概述 </font>
# (1) 基本概念
  • java.time.LocalDate 类主要用于描述年 - 月 - 日格式的日期信息,该类不表示时间和时区信息
# (2) 常用的方法
方法声明功能介绍
static LocalDate new()在默认时区中从系统时钟获取当前日期
# <font size = 4>3.3 LocalTime 类的概述 </font>
# (1) 基本概念
  • java.time.LocalTime 类主要用于描述时间信息,可以描述时分秒以及纳秒
# (2) 常用的方法
方法声明功能介绍
static LocalTime now()从默认时区的系统时间中获取当前时间
static LocalTime now(ZoneId zone)获取指定时区的当前时间
# <font size = 4>3.4LocalDateTime 类的概述 </font>
# (1) 基本概念
  • java.time.LocalDateTime 类主要用于描述 ISO-8601 日历系统中没有时区的日期时间,如 2007-12-03T10:15:30

<font color = red> 方法使用总共分为: 获取指定增加减少 </font>

方法声明功能介绍
static LocalDateTime now()从默认时区的系统时间中获取当前日期时间
static LocalDateTime of(int year,int month,int dayOfMonth,int hour,int minute,int second)根据参数指定的年月日时分秒信息来设置日期时间
int getYear()获取年份字段的数值
int getMonthValue()获取 1 到 12 之间的月份字段
int getDayOfMonth()获取日期字段
int getHour()获取小时数
int getMinute()获取分钟数
int getSecond()获取秒数
LocalDateTime withYear(int year)设置为参数指定的年
LocalDateTime withMonth(int month)设置为参数指定的月
LocalDateTime withDayOfMonth(int dayOfMonth)设置为参数指定的日
LocalDateTime withHour(int hour)设置为参数指定的时
LocalDateTime withMinute(int minute)设置为参数指定的分
LocalDateTime withSecond(int second)设置为参数指定的秒
LocalDateTime plusYears(long years)加上参数指定的年
LocalDateTime plusmonths(long months)加上参数指定的月
LocalDateTime plusDays(long days)加上参数指定的日
LocalDateTime plusHours(long hours)加上参数指定的时
LocalDateTime plusMinutes(long minutes)加上参数指定的分
LocalDateTime plusSeconds(long seconds)加上参数指定的秒
LocalDateTime minusYears(long years)减去参数指定的年
LocalDateTime minuMonths(long months)减去参数指定的月
LocalDateTime minusDays(long days)减去参数指定的日
LocalDateTime minusHours(long hours)减去参数指定的时
LocalDateTime minusMinutes(long minutes)减去参数指定的分
LocalDateTime minusSeconds(long seconds)减去参数指定的秒
  • 根据所有代码演示
LocalDateTime of = LocalDateTime.of(2008,10,10,5,6,7);
//"-------- 设置 year:2012-------"
System.out.println("----------设置Year为:2012-----------");
LocalDateTime of1 = of.withYear(2012);
System.out.println("year: "+of1);
//"-------- 增加 month:2-------"
LocalDateTime of2 = of.plusMonths(2);
System.out.println("month: "+of2);
//"--------- 减少 day:9----------"
LocalDateTime of3 = of.minusDays(9);
System.out.println("day: "+of3);
//"--------- 增加 hour:6---------"
LocalDateTime of4 = of.plusHours(6);
System.out.println("hour: "+of4);
//"-------- 设置 minute:40--------"
LocalDateTime of5 = of.withMinute(40);
System.out.println("minute: "+of5);
//"-------- 减少 second:6---------"
LocalDateTime of6 = of.minusSeconds(6);
System.out.println("second: "+of6+"\n");
// 由此可见 LocalDateTime 返回的是一个新的对象它与 String 类似,并不是在原有的对象中进行修改
//----------LocalDateTime 对象的值 ----------
System.out.println("of: "+of);//2008-10-10T00:00
# <font size = 4>3.5 Instant 类的概述 </font>
# (1) 基本概念
  • java.time.Instant 类主要用于描述瞬间的时间点信息
# (2) 常用的方法
方法声明功能介绍
static Instant now()从系统时钟上获取当前时间
OffsetDateTime atOffset(ZoneOffset offset)将此瞬间与偏移量组合以创建偏移量日期时间
static Instant ofEpochMilli(long epochMilli)根据参数指定的毫秒数来构造对象,参数为距离 1970 年 1 月 1 日 0 时 0 分 0 秒的毫秒值
long toEpochMilli()获取距离 1970 年 1 月 1 日 0 时 0 分 0 秒的毫秒值
// 从默认时区的系统时间中获取当前日期时间
LocalDateTime datetime = LocalDateTime.now();
System.out.println("localdatetime: "+datetime);
// 从系统时钟上获取当前时间
Instant in = Instant.now();
System.out.println("获取当前的时间为: "+in);
// 从此瞬间与偏移量组成以创建偏移量日期时间
OffsetDateTime offsetDateTime = in.atOffset(ZoneOffset.ofHours(8));
System.out.println("获取修改后的时间为: "+offsetDateTime);
// 获取距离 1970-1-1-0-0-0 的毫秒值
long l = in.toEpochMilli();
System.out.println("toEpochMilli: "+l);
// 根据参数指定的毫秒值构造对象
Instant x = Instant.ofEpochMilli(l);
System.out.println("ofEpochMilli: "+x);
# <font size = 4>3.5.1 DateTimeFormatter 类的概述 </font>
# (1) 基本概念
  • java.time.format.DateTimeFormatter 类主要用于格式化和解析日期
# (2) 常用的方法
方法声明功能介绍
static DateTimeFormatter ofPattern(String pattern)根据参数指定的模式来获取对象
String format(TempporalAccessor temporal)将参数指定日期时间转换为字符串
TemporalAccessor parse(CharSequence text)将参数指定字符串转换为日期时间
// 获取当前系统日期和时间
LocalDateTime ld = LocalDateTime.now();
// 通过 ofPattern 获取自定义模式的 DateTimeFormatter 格式化对象 构造器中定义日期时间格式
DateTimeFormatter tter = DateTimeFormatter.ofPattern("yyyy-MM-dd EH:mm:ss");
// 对象名调用 format 将日期时间格式化为日期时间字符串
String tter1 = tter.format(ld);
System.out.println(tter1);
// 通过 ofLocalizedDateTime 获取格式化对象 构造器中赋值通过 FormatStyle 调用的格式
//FULL 完整格式,LONG 长格式,SHORT 短格式,MEDIUM 普通格式
DateTimeFormatter tt = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG,FormatStyle.SHORT);
String tt1 = tt.format(ld);
System.out.println(tt1);
// 通过对象名调用 parse 将日期时间字符串解析为 Date 日期时间
TemporalAccessor parse = tter.parse(tter1);
System.out.println(parse);
// 定义改对象的时间类型
String x1 = "2022-09-01 周四11:42:29";
// 通过 LocalDateTime 调用 parse 构造器中传入时间类型与该时间的对象将其解析为 Date 类型的日期时间
LocalDateTime x = LocalDateTime.parse(x1,tter);
System.out.println(x);
// 与上同理
String ar = "2022年9月1日 上午11:45";
LocalDateTime ar1 = LocalDateTime.parse(ar,tt);
System.out.println(ar1);