一、String类
(一)概述
String:字符串,使用一对””引起来表示。
String声明为final的,不可被继承
String 实现了
Serializable
接口:表示字符串是支持序列化的。 实现了Comparable
接口:表示String可以比较大小String内部定义了
final char[] value
用于存储字符串数据String:代表不可变的字符序列。简称:不可变性。
体现:
4.1.当对字符串重新赋值时,需要重写指定内存区域赋值,不能使用原有的value进行赋值。
4.2.当对现有的字符串进行连接操作时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值。
4.3.当调用String的
replace()
方法修改指定字符或字符串时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值。通过字面量的方式(区别于new给一个字符串赋值,此时的字符串值声明在字符串常量池中)。
字符串常量池中是不会存储相同内容(使用String类的equals()比较,返回true)的字符串的)。
(二)String的特性
String类:代表字符串。Java程序中的所有字符串字面值(如”abc”)都作为此类的实例实现。 String是一个final类,代表不可变的字符序列。 字符串是常量,用双引号引起来表示。它们的值在创建之后不能更改。 String对象的字符内容是存储在一个字符数组vaue中的。
**String源码构造器:**(JDK8)
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char[] value;
/** Cache the hash code for the string */
private int hash; // Default to 0
注:JDK9之后用的是byte[]数组存储value
1. String的不可变性
1.1 说明:
- 当对字符串重新赋值时,需要重写指定内存区域赋值,不能使用原有的value进行赋值。
- 当对现的字符串进行连接操作时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值。
- 当调用String的
replace()
方法修改指定字符或字符串时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值。
1.2 代码举例:
String s1 = "abc";//通过字面量的定义方式
String s2 = "abc";
s1 = "hello";
System.out.println(s1 == s2); //false 比较s1与s2的地址值
System.out.println(s1);//hello
System.out.println(s2);//def
System.out.println("-----------------------");
String s3 = "abc";
s3 += "def";
System.out.println(s3);//abcdef
System.out.println(s2);//def
System.out.println("-----------------------");
String s4 ="test";
String s5 = s4.replace("t","b");
System.out.println(s4);//test
System.out.println(s5);//besb
2. String实例化方法
2.1 实现方式说明:
- 方式一:通过字面量定义的方式
- 方式二:通过new + 构造器的方式
面试题:
String s = new String("abc");
方式创建对象,在内存中创建了几个对象?
两个:一个是堆空间中new结构,另一个是char[]
对应的常量池中的数据:”abc”
2.2 代码实例:
//通过字面量定义的方式:此时的s1和s2的数据javaEE声明在方法区中的字符串常量池中。
String s1 = "javaEE";
String s2 = "javaEE";
//通过new + 构造器的方式:此时的s3和s4保存的地址值,是数据在堆空间中开辟空间以后对应的地址值。
String s3 = new String("javaEE");
String s4 = new String("javaEE");
System.out.println(s1 == s2);//true
System.out.println(s1 == s3);//false
System.out.println(s1 == s4);//false
System.out.println(s3 == s4);//false
复制代码
String str1=“abc”;
与 String str2= new String(“abc”);
的区别?
新建String对象的内存解析
3. 字符串拼接方式赋值对比
3.1说明:
- 常量与常量的拼接结果在常量池。且常量池中不会存在相同内容的常量。
- 只要其中一个是变量,结果就在堆中。
- 如果拼接的结果调用
intern()
方法,返回值就在常量池中
3.2 代码示例
String s1 = "javaEE";
String s2 = "hadoop";
String s3 = "javaEEhadoop";
String s4 = "javaEE" + "hadoop";
String s5 = s1 + "hadoop";
String s6 = "javaEE" + s2;
String s7 = s1 + s2;
System.out.println(s3 == s4);//true
System.out.println(s3 == s5);//false
System.out.println(s3 == s6);//false
System.out.println(s3 == s7);//false
System.out.println(s5 == s6);//false
System.out.println(s5 == s7);//false
System.out.println(s6 == s7);//false
String s8 = s6.intern();//返回值得到的s8使用的常量值中已经存在的“javaEEhadoop”
System.out.println(s3 == s8);//true
****************************
String s1 = "javaEEhadoop";
String s2 = "javaEE";
String s3 = s2 + "hadoop";
System.out.println(s1 == s3);//false
final String s4 = "javaEE";//s4:常量
String s5 = s4 + "hadoop";
System.out.println(s1 == s5);//true
4. String使用陷阱
String s1="a";
说明:在字符串常量池中创建了一个字面量为”a”的字符串。
s1=s1+”b”
说明:实际上原来的“a”字符串对象已经丢弃了,现在在堆空间中产生了一个字符串s1+”b”(也就是”ab”)。如果多次执行这些改变串内容的操作,会导致大量副本字符串对象存留在内存中,降低效率。如果这样的操作放到循环中,会极大影响程序的性能。
String s2="ab";
说明:直接在字符串常量池中创建一个字面量为”ab”的字符串。String s3="a"+"b";
说明:s3指向字符串常量池中已经创建的”ab”的字符串。String s4=s1.intern();
说明:堆空间的S1对象在调用 intern()之后,会将常量池中已经存在的”ab”字符串赋值给s4。
5. String类常用方法
5.1 字符串操作
操作字符:
int length()
:返回字符串的长度:return value.length
char charAt(int index)
: 返回某索引处的字符return value[index]
boolean isEmpty()
:判断是否是空字符串:return value.length == 0
String toLowerCase()
:使用默认语言环境,将 String 中的所字符转换为小写String toUpperCase()
:使用默认语言环境,将 String 中的所字符转换为大写String trim()
:返回字符串的副本,忽略前导空白和尾部空白boolean equals(Object obj)
:比较字符串的内容是否相同boolean equalsIgnoreCase(String anotherString)
:与equals()
方法类似,忽略大小写String concat(String str)
:将指定字符串连接到此字符串的结尾。 等价于用+
int compareTo(String anotherString)
:比较两个字符串的大小String substring(int beginIndex)
:返回一个新的字符串,它是此字符串的从beginIndex 开始截取到最后的一个子字符串。String substring(int beginIndex, int endIndex)
:返回一个新字符串,它是此字符串从 beginIndex 开始截取到 endIndex (不包含)的一个子字符串。
判断字符:
boolean endsWith(String suffix)
:测试此字符串是否以指定的后缀结束boolean startsWith(String prefix)
:测试此字符串是否以指定的前缀开始boolean startsWith(String prefix, int toffset)
:测试此字符串从指定索引开始的子字符串是否以指定前缀开始
@Test
public void test3() {
String s1 = "javaEE";
System.out.println(s1.endsWith("EE"));//true
System.out.println(s1.startsWith("a"));//false
System.out.println(s1.startsWith("EE", 4));//true
}
5.2 查找字符串中的字符
boolean contains(CharSequence s):
当且仅当此字符串包含指定的 char 值序列时,返回 trueint indexOf(String str)
:返回指定子字符串在此字符串中第一次出现处的索引int indexOf(String str, int fromIndex)
:返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始int lastIndexOf(String str)
:返回指定子字符串在此字符串中最右边出现处的索引int lastIndexOf(String str, int fromIndex)
:返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索
注:
indexOf
和lastIndexOf
方法如果未找到都是返回-1
代码示例:
@Test
public void test3() {
String s2="hello word";
System.out.println(s2.contains("o"));//true
System.out.println(s2.indexOf("h"));//0
System.out.println(s2.indexOf("o", 5));//7
System.out.println(s2.lastIndexOf("o"));//7
System.out.println(s2.lastIndexOf("l", 2));//2
}
5.3 字符串操作方法
- 替换:
String replace(char oldChar, char newChar)
:返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所 oldChar 得到的。String replace(CharSequence target, CharSequence replacement)
:使用指定的字面值替换序列替换此字符串所匹配字面值目标序列的子字符串。String replaceAll(String regex, String replacement)
:使用给定的 replacement 替换此字符串所匹配给定的正则表达式的子字符串。String replaceFirst(String regex, String replacement)
:使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。
- 匹配:
boolean matches(String regex)
:告知此字符串是否匹配给定的正则表达式。
- 切片:
String[] split(String regex)
:根据给定正则表达式的匹配拆分此字符串。String[] split(String regex, int limit)
:根据匹配给定的正则表达式来拆分此字符串,最多不超过limit个,如果超过了,剩下的全部都放到最后一个元素中。
代码示例:
@Test
public void test4() {
String str1 = "北京你好,你好北京";
String str2 = str1.replace('北', '南');
System.out.println(str1);//北京你好,你好北京
System.out.println(str2);//南京你好,你好南京
String str3 = str1.replace("北京", "上海");
System.out.println(str3);//上海你好,你好上海
System.out.println("*************************");
String str = "12hello34world5java7891mysql456";
//把字符串中的数字替换成,,如果结果中开头和结尾有,的话去掉
String string = str.replaceAll("\\d+", ",").replaceAll("^,|,$", "");
System.out.println(string);//hello,world,java,mysql
System.out.println("*************************");
str = "12345";
//判断str字符串中是否全部有数字组成,即有1-n个数字组成
boolean matches = str.matches("\\d+");
System.out.println(matches);//true
String tel = "0571-4534289";
//判断这是否是一个杭州的固定电话
boolean result = tel.matches("0571-\\d{7,8}");
System.out.println(result);//true
System.out.println("*************************");
str = "hello|world|java";
String[] strs = str.split("\\|");
for (int i = 0; i < strs.length; i++) {
System.out.println(strs[i]);//依次输出hello word java
}
System.out.println();
str2 = "hello.world.java";
String[] strs2 = str2.split("\\.");
for (int i = 0; i < strs2.length; i++) {
System.out.println(strs2[i]);//依次输出hello word java
}
}
6. String与其他结构的转换
6.1 String与基本数据类型、包装类之间的转换
String –> 基本数据类型、包装类:调用包装类的静态方法:parseXxx(str)
基本数据类型、包装类 –> String:调用String重载的 valueOf(xxx)
代码示例:
@Test
public void StringToBasic() {
String str1 = "123";
int i = Integer.parseInt(str1);
System.out.println(i);
System.out.println(i == 123);//true
int j = 456;
String s = String.valueOf(j);
System.out.println(s);
System.out.println(s.equals("456"));//true
}
6.2 与字符数组之间的转换
String –> char[]:调用String的 toCharArray() char[]
–> String:调用String的构造器
代码示例:
@Test
public void BasicToString() {
String s1 = "helloword";
char[] chars = s1.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.println(chars[i]);
}
char[] charArray = new char[]{'h', 'e', 'l', 'l', 'o'};
String s2 = new String(charArray);
System.out.println(s2);
}
6.3 与字节数组之间的转换
编码:String –> byte[]:调用String的 getBytes()
解码:byte[] –> String:调用String的构造器
说明:解码时,要求解码使用的字符集必须与编码时使用的字符集一致,否则会出现乱码。
@Test
public void StringToByteTest() throws UnsupportedEncodingException {
String s1 ="你好java世界";
byte[] bytesArray = s1.getBytes();//使用默认字符集编码
System.out.println(Arrays.toString(bytesArray));//[-28, -67, -96, -27, -91, -67, 106, 97, 118, 97, -28, -72, -106, -25, -107, -116]
byte[] gbks = s1.getBytes("gbk");//使用gbk编码集合
System.out.println(Arrays.toString(gbks));//[-60, -29, -70, -61, 106, 97, 118, 97, -54, -64, -67, -25]
System.out.println("--------------------------------");
String str1=new String(bytesArray);//使用默认字符进行解码
System.out.println(str1);//你好java世界
String str2 = new String(gbks);//使用默认字符对gbk编码进行解码
System.out.println(str2);//���java���� 解码错误,出现中文乱码,原因:编码和解码不一致
String str3 = new String(gbks,"gbk");//使用gbk格式进行解码
System.out.println(str3);//你好java世界,解码正确,原因:编码和解码一致
}
6.4 与StringBuffer、StringBuilder之间的转换
1.String –>StringBuffer、StringBuilder: 调用StringBuffer、StringBuilder构造器
2.StringBuffer、StringBuilder –>String:
①调用String构造器; ②StringBuffer、StringBuilder的toString()
7. JVM中字符串常量池存放位置说明:
jdk 1.6:字符串常量池存储在方法区(永久代)
jdk 1.7及之后:字符串常量池存储在堆空间
二、StringBuffer和StringBuilder
(一)StringBuffer类
1.概述:
abstract class AbstractStringBuilder implements Appendable, CharSequence {
/**
* The value is used for character storage.
*/
char[] value;//value没有final声明,value可以不断扩容
/**
* The count is the number of characters used.
*/
int count;//count记录有效字符个数
- StringBuffer类不同于 String,其对象必须使用构造器生成。
- 有三个构造器:
StringBuffer()
:初始容量为16的字符串缓冲区StringBuffer(int size)
:构造指定容量的字符串缓冲区StringBuffer(String str)
:将内容初始化为指定字符串内容
String s= new String("我喜欢学习");
StringBuffer buffer= new StringBuffer("我喜欢学习");
buffer. append("数学");
2.常用方法:
增:append(xxx)
;
删:delete(int start,int end)
;
改:setCharAt(int n ,char ch)
/ replace(int start, int end, String str)
;
查:charAt(int n )
;
插:insert(int offset, xxx)
;
长度:length()
;
遍历:for() + charAt()
/ toString()
;
代码示例:
@Test
public void stringBufferMethodTest(){
StringBuffer s1 = new StringBuffer("abc");
System.out.println(s1);
System.out.println(s1.append("1"));//abc1
System.out.println(s1.delete(0, 1));//bc1
System.out.println(s1.replace(0, 1, "hello"));//helloc1
System.out.println(s1.insert(3, "v"));//helvloc1
System.out.println(s1.reverse());//1colvleh
}
(二)StringBuilder类
StringBuilder和 StringBuffer非常类似,均代表可变的字符序列,而且提供相关功能的方法也一样,只是StringBuilder类没有加线程锁,执行效率更高。
1. String、StringBuffer、StringBuilder三者的对比
- String:不可变的字符序列;底层使用
char[]
(JDK8) 存储;占用内存(会不断的创建和回收对象) - StringBuffer:可变的字符序列;线程安全的,效率低;线程安全;底层使用
char[]
存储; - StringBuilder:可变的字符序列;jdk5.0新增的,线程不安全的,效率高;线程不安全;底层使用
char[]
存储
2. StringBuffer与StringBuilder的内存解析
以StringBuffer为例:
String str = new String();//char[] value = new char[0];
String str1 = new String("abc");//char[] value = new char[]{'a','b','c'};
StringBuffer sb1 = new StringBuffer();//char[] value = new char[16];底层创建了一个长度是16的数组。
System.out.println(sb1.length());//
sb1.append('a');//value[0] = 'a';
sb1.append('b');//value[1] = 'b';
StringBuffer sb2 = new StringBuffer("abc");//char[] value = new char["abc".length() + 16];
扩容问题:如果要添加的数据底层数组盛不下了,那就需要扩容底层的数组。 默认情况下,扩容为原来容量的2倍 + 2,同时将原有数组中的元素复制到新的数组中。
指导意义:开发中建议大家使用:StringBuffer(int capacity)
或 StringBuilder(int capacity)
3. 对比String、StringBuffer、StringBuilder三者的执行效率
从高到低排列:StringBuilder > StringBuffer > String
@Test
public void test3(){
//初始设置
long startTime = 0L;
long endTime = 0L;
String text = "";
StringBuffer buffer = new StringBuffer("");
StringBuilder builder = new StringBuilder("");
//开始对比
startTime = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
buffer.append(String.valueOf(i));
}
endTime = System.currentTimeMillis();
System.out.println("StringBuffer的执行时间:" + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
builder.append(String.valueOf(i));
}
endTime = System.currentTimeMillis();
System.out.println("StringBuilder的执行时间:" + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
text = text + i;
}
endTime = System.currentTimeMillis();
System.out.println("String的执行时间:" + (endTime - startTime));
}
三、JDK 8.0以前的日期时间API
1. java.lang.System
类
System类提供的 public static long currentTimeMillis()
用来返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差。(时间戳) 此方法适于计算时间差。
计算世界时间的主要标准有:
- UTC(Coordinated Universal Time)
- GMT(Greenwich Mean Time)
- CST(Central Standard Time)
代码示例:
//获取系统当前时间:System类中的currentTimeMillis()
long time = System.currentTimeMillis();
//返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差。
//称为时间戳
System.out.println(time);
2. java.util.Date
类
表示特定的瞬间,精确到毫秒
2.1 构造器
Date()
:使用无参的构造器创建对象可以获取本地当前时间
Date(long date)
2.2 常用方法
getTime()
:返回自1970年1月1日00:00:00GMT以来此Date对象表示的毫秒数
tostring()
:把此Date对象转换为以下形式的 String:
- dow mon dd
- hh: mm:ss zzz yyyy
其中:doW是一周中的某一天(Sun,Mon,Tue,Wed,Thu,Fri,Sat),zzz是时间标准。 其它很多方法都过时了
2.3 java.util.Date类与java.sql.Date
类
java.util.Date
类java.sql.Date
类
1.两个构造器的使用
- 构造器一:
Date()
:创建一个对应当前时间的Date对象 - 构造器二:创建指定毫秒数的Date对象
2.两个方法的使用
toString()
:显示当前的年、月、日、时、分、秒getTime()
:获取当前Date对象对应的毫秒数。(时间戳)
3.java.sql.Date
对应着数据库中的日期类型的变量
如何将 java.util.Date
对象转换为 java.sql.Date
对象
@Test
public void dateTest(){
//构造器一:Date():创建一个对应当前时间的Date对象
Date date1 = new Date();
System.out.println(date1.toString());//Sun Apr 19 13:35:12 CST 2020
System.out.println(date1.getTime());//1587274512876
//构造器二:创建指定毫秒数的Date对象
Date date2 = new Date(15872745176L);
System.out.println(date2.toString());
System.out.println("-----------------------");
//创建java.sql.Date对象
java.sql.Date date3 = new java.sql.Date(1587274512876L);
System.out.println(date3.toString());
//如何将java.util.Date对象转换为java.sql.Date对象
Date date4 = new Date();
//第一种方式,存在问题:java.util.Date cannot be cast to java.sql.Date
// java.sql.Date date6 = (java.sql.Date) date4;
// System.out.println(date6);
//第二种方式
java.sql.Date date5 = new java.sql.Date(date4.getTime());
System.out.println(date5);
}
3. java.text.SimpleDateFormat
类
Date类的AP不易于国际化,大部分被废弃了, java.text.SimpleDateFormat
类是一个不与语言环境有关的方式来格式化和解析日期的具体类。
它允许进行格式化:日期→文本、解析:文本→日期
SimpleDateFormat()
:默认的模式和语言环境创建对象
public SimpleDateFormat(String pattern)
:该构造方法可以用参数 pattern指定的格式创建一个对象,该对象调用:
public String format(Datedate)
:方法格式化时间对象date
public Date parse(String source)
:从给定字符串的开始解析文本,以生成个日期
1. SimpleDateFormat对日期Date类的格式化和解析
两个操作:
1.1 格式化:日期 —>字符串
1.2 解析:格式化的逆过程,字符串 —> 日期
2. SimpleDateFormat
的实例化:new + 构造器
照指定的方式格式化和解析:调用带参的构造器
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
代码示例:
@Test
public void test2() throws ParseException {
//实例化Date对象
Date date1 = new Date();
//实例化SimpleDateFormate对象,并设置显示格式
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:aaa");
//格式化date对象
String format = simpleDateFormat.format(date1);
System.out.println(format.toString());//2020-09-19 02:09:下午
//解析:要求字符串必须是符合SimpleDateFormat识别的格式(通过构造器参数体现),
//否则,抛异常
Date date2 = simpleDateFormat.parse("2020-04-20 14:20:下午");
System.out.println(date2.toString());//Tue Jan 21 02:20:00 CST 2020
}
4. Calendar类:日历类、抽象类
Calendar是一个抽象基类,主用用于完成日期字段之间相互操作的功能。
- 获取 Calenda实例的方法 使用 Calendar.getInstance()方法 调用它的子类 GregorianCalendarl的构造器。
- 一个 Calendar的实例是系统时间的抽象表示,通过 get(int field)方法来取得想要的时间信息。 比如YEAR、MONTH、DAY_OF_WEEK、HOUR_OF_DAY、MINUTE、SECOND
注意: 获取月份时:一月是0,二月是1,以此类推,12月是11 获取星期时:周日是1,周二是2,。。。周六是7
4.1 实例化
方式一:创建其子类(GregorianCalendar)的对象
方式二:调用其静态方法 getInstance()
4.2 常用方法
get()
:获取日期
set()
:设置日期
add()
:添加、修改日期
getTime
:日历类–>Date
setTime
:Date–>日历类
代码示例:
Calendar calendar = Calendar.getInstance();
// System.out.println(calendar.getClass());
//2.常用方法
//get()
int days = calendar.get(Calendar.DAY_OF_MONTH);//获取本月第几天
System.out.println(days);
System.out.println(calendar.get(Calendar.DAY_OF_YEAR));//获取本年第几天
//set()
//calendar可变性
calendar.set(Calendar.DAY_OF_MONTH,22);//设置本月第几天
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days);
//add()
calendar.add(Calendar.DAY_OF_MONTH,-3);
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days);
//getTime():日历类---> Date
Date date = calendar.getTime();
System.out.println(date);
//setTime():Date ---> 日历类
Date date1 = new Date();
calendar.setTime(date1);
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days);
四、JDK 8.0中新的日期时间类
1. 日期时间API的迭代:
第一代:jdk 1.0 Date类
第二代:jdk 1.1 Calendar类,一定程度上替换Date类
第三代:jdk 1.8 提出了新的一套API
2. 前两代的问题:
可变性:像日期和时间这样的类应该是不可变的。
偏移性:Date中的年份是从1900开始的,而月份都从0开始。
格式化:格式化只对Date用,Calendar则不行。 此外,它们也不是线程安全的;不能处理闰秒等。
Java 8.0中新引入的java.time API:
Java 8.0吸收了Joda-Time的精华,以一个新的开始为Java创建优秀的APl。新的java.time中包含了所有关于本地日期(LocalDate)、本地时间(Localtime)、本地日期时间(LocalDate time)、时区(ZonedDate time)和持续时间(Duration)的类。历史悠久的Date类新增了tolnstant()方法用于把Date转换成新的表示形式。这些新增的本地化时间日期API大大简化了日期时间和本地化的管理。
3. Java 8.0中新的日期时间API涉及的包:
4. 本地日期、本地时间、本地日期时间的使用:
LocalDate / LocalTime / LocalDateTime
4.1 说明:
① 分别表示使用 ISO-8601日历系统的日期、时间、日期和时间。它们提供了简单的本地日期或时间,并不包含当前的时间信息,也不包含与时区相关的信息。
② LocalDateTime相较于LocalDate、LocalTime,使用频率要高
③ 类似于Calendar
4.2 常用方法:
代码示例:
@Test
public void test1(){
//now():获取当前的日期、时间、日期时间
LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDate);//2020-04-21
System.out.println(localTime);//18:52:54.929
System.out.println(localDateTime);//2020-04-21T18:52:54.929
//of():设置指定的年、月、日、时、分、秒。没有偏移量
LocalDateTime localDateTime1 = LocalDateTime.of(2020,10,6,12,13,12);
System.out.println(localDateTime1);//2020-10-06T12:13:12
//getXxx():获取相关的属性
System.out.println(localDateTime.getDayOfMonth());//21
System.out.println(localDateTime.getDayOfWeek());//TUESDAY
System.out.println(localDateTime.getMonth());//APRIL
System.out.println(localDateTime.getMonthValue());//4
System.out.println(localDateTime.getMinute());//52
//体现不可变性
//withXxx():设置相关的属性
LocalDate localDate1 = localDate.withDayOfMonth(22);
System.out.println(localDate);//2020-04-21
System.out.println(localDate1);//2020-04-22
LocalDateTime localDateTime2 = localDateTime.withHour(4);
System.out.println(localDateTime);//2020-04-21T18:59:17.484
System.out.println(localDateTime2);//2020-04-21T04:59:17.484
//不可变性
LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
System.out.println(localDateTime);//2020-04-21T18:59:17.484
System.out.println(localDateTime3);//2020-07-21T18:59:17.484
LocalDateTime localDateTime4 = localDateTime.minusDays(6);
System.out.println(localDateTime);//2020-04-21T18:59:17.484
System.out.println(localDateTime4);//2020-04-15T18:59:17.484
}
5.时间点:Instant
5.1 说明:
① 时间线上的一个瞬时点。 概念上讲,它只是简单的表示自1970年1月1日0时0分0秒(UTC开始的秒数。)
② 类似于 java.util.Date
类
5.2 常用方法:
代码示例:
@Test
public void test2(){
//now():获取本初子午线对应的标准时间
Instant instant = Instant.now();
System.out.println(instant);//2020-04-21T11:03:21.469Z
//添加时间的偏移量
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime);//2020-04-21T19:03:21.469+08:00
//toEpochMilli():获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数 ---> Date类的getTime()
long milli = instant.toEpochMilli();
System.out.println(milli);//1587467105795
//ofEpochMilli():通过给定的毫秒数,获取Instant实例 -->Date(long millis)
Instant instant1 = Instant.ofEpochMilli(1587467105795L);
System.out.println(instant1);//2020-04-21T11:05:05.795Z
}
6.日期时间格式化类:DateTimeFormatter
6.1 说明:
① 格式化或解析日期、时间
② 类似于 SimpleDateFormat
6.2 常用方法:
- 实例化方法
- 预定义的标准格式。如:``ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME` 本地化相关的格式:
- 如:
ofLocalizedDateTime(FormatStyle.LONG)
- 自定义的格式:如:
ofPattern(“yyyy-MM-dd hh:mm:ss”)
常用方法:
代码示例:
@Test public void test3(){ // 方式一:预定义的标准格式。 // 如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; //格式化:日期-->字符串 LocalDateTime localDateTime = LocalDateTime.now(); String str1 = formatter.format(localDateTime); System.out.println(localDateTime);//2020-04-21T19:13:13.530 System.out.println(str1);//2020-04-21T19:13:13.53 //解析:字符串 -->日期 TemporalAccessor parse = formatter.parse("2000-04-21T19:13:13.53"); System.out.println(parse);//{},ISO resolved to 2000-04-21T19:13:13.530 // 方式二: // 本地化相关的格式。如:ofLocalizedDateTime() // FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG); //格式化 String str2 = formatter1.format(localDateTime); System.out.println(str2);//2020年4月21日 下午07时16分57秒 // 本地化相关的格式。如:ofLocalizedDate() // FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM); //格式化 String str3 = formatter2.format(LocalDate.now()); System.out.println(str3);//2020-4-21 // 重点: 方式三:自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”) DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); String Str4 = formatter3.format(LocalDateTime.now()); System.out.println(Str4);//2020-04-21 07:24:04 TemporalAccessor accessor = formatter3.parse("2020-02-03 05:23:06"); System.out.println(accessor);//{SecondOfMinute=6, HourOfAmPm=5, NanoOfSecond=0, MicroOfSecond=0, MinuteOfHour=23, MilliOfSecond=0},ISO resolved to 2020-02-03 }
7.其它API的使用:
7.1 带时区的日期时间:
ZonedDateTime / ZoneId
代码示例:
// ZoneId:类中包含了所的时区信息
@Test
public void test1(){
//getAvailableZoneIds():获取所的ZoneId
Set<String> zoneIds = ZoneId.getAvailableZoneIds();
for(String s : zoneIds){
System.out.println(s);
}
System.out.println();
//获取“Asia/Tokyo”时区对应的时间
LocalDateTime localDateTime = LocalDateTime.now(ZoneId.of("Asia/Tokyo"));
System.out.println(localDateTime);
}
//ZonedDateTime:带时区的日期时间
@Test
public void test2(){
//now():获取本时区的ZonedDateTime对象
ZonedDateTime zonedDateTime = ZonedDateTime.now();
System.out.println(zonedDateTime);
//now(ZoneId id):获取指定时区的ZonedDateTime对象
ZonedDateTime zonedDateTime1 = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
System.out.println(zonedDateTime1);
}
7.2 时间间隔:
Duration
–用于计算两个“时间”间隔,以秒和纳秒为基准
代码示例:
@Test
public void test3(){
LocalTime localTime = LocalTime.now();
LocalTime localTime1 = LocalTime.of(15, 23, 32);
//between():静态方法,返回Duration对象,表示两个时间的间隔
Duration duration = Duration.between(localTime1, localTime);
System.out.println(duration);
System.out.println(duration.getSeconds());
System.out.println(duration.getNano());
LocalDateTime localDateTime = LocalDateTime.of(2016, 6, 12, 15, 23, 32);
LocalDateTime localDateTime1 = LocalDateTime.of(2017, 6, 12, 15, 23, 32);
Duration duration1 = Duration.between(localDateTime1, localDateTime);
System.out.println(duration1.toDays());
}
7.3 日期间隔:
Period
–用于计算两个“日期”间隔,以年、月、日衡量
代码示例:
@Test
public void test4(){
LocalDate localDate = LocalDate.now();
LocalDate localDate1 = LocalDate.of(2028, 3, 18);
Period period = Period.between(localDate, localDate1);
System.out.println(period);
System.out.println(period.getYears());
System.out.println(period.getMonths());
System.out.println(period.getDays());
Period period1 = period.withYears(2);
System.out.println(period1);
}
7.4 日期时间校正器:TemporalAdjuster
代码示例:
@Test
public void test5(){
//获取当前日期的下一个周日是哪天?
TemporalAdjuster temporalAdjuster = TemporalAdjusters.next(DayOfWeek.SUNDAY);
LocalDateTime localDateTime = LocalDateTime.now().with(temporalAdjuster);
System.out.println(localDateTime);
//获取下一个工作日是哪天?
LocalDate localDate = LocalDate.now().with(new TemporalAdjuster(){
@Override
public Temporal adjustInto(Temporal temporal) {
LocalDate date = (LocalDate)temporal;
if(date.getDayOfWeek().equals(DayOfWeek.FRIDAY)){
return date.plusDays(3);
}else if(date.getDayOfWeek().equals(DayOfWeek.SATURDAY)){
return date.plusDays(2);
}else{
return date.plusDays(1);
}
}
});
System.out.println("下一个工作日是:" + localDate);
}
复制代码
7.5 新的日期API与原来API的转化问题:
五、Java比较器
1. Java比较器的使用背景:
- Java中的对象,正常情况下,只能进行比较:
==
或!=
。不能使用>
或<
的 - 但是在开发场景中,我们需要对多个对象进行排序,言外之意,就需要比较对象的大小。
- 如何实现?使用两个接口中的任何一个:Comparable(自然排序) 或 Comparator(定制排序)
2. 自然排序:使用Comparable接口
2.1 说明
- 像 String 或包装类等实现了Comparable接口,重写了
compareTo(obj)
方法,给出了比较两个对象大小的方式。 - 像 String 或包装类重写
compareTo()
方法以后,进行了从小到大的排列 - 重写
compareTo(obj)
的规则: 如果当前对象this大于形参对象obj,则返回正整数, 如果当前对象this小于形参对象obj,则返回负整数, 如果当前对象this等于形参对象obj,则返回零。 - 对于自定义类来说,如果需要排序,我们可以让自定义类实现Comparable接口,重写
compareTo(obj)
方法。在compareTo(obj)
方法中指明如何排序 - Comparable的典型实现:(默认都是从小到大排列的) String:按照字符串中字符的Uincode值进行比较 Character:按照字符的 Unicode值来进行比较 数值类型对应的包装类以及 BigInteger、BigDecimal:按照它们对应的数值大小进行比较 Boolean:true对应的包装类实例大于false对应的包装类实例 Date、Time等:后面的日期时间比前面的日期时间大
2.2 自定义类代码举例:
public class Goods implements Comparable{
private String name;
private double price;
//指明商品比较大小的方式:照价格从低到高排序,再照产品名称从高到低排序
@Override
public int compareTo(Object o) {
// System.out.println("**************");
if(o instanceof Goods){
Goods goods = (Goods)o;
//方式一:
if(this.price > goods.price){
return 1;
}else if(this.price < goods.price){
return -1;
}else{
// return 0;
return -this.name.compareTo(goods.name);
}
//方式二:
// return Double.compare(this.price,goods.price);
}
// return 0;
throw new RuntimeException("传入的数据类型不一致!");
}
// getter、setter、toString()、构造器:省略
}
3. 定制排序:使用Comparator接口
3.1 说明:
- 背景:
当元素的类型没实现 java.lang.Comparable
接口而又不方便修改代码,或者实现了java.lang.Comparable接口的排序规则不适合当前的操作,那么可以考虑使用 Comparator 的对象来排序
- 重写
compare(Object o1,Object o2)
方法,比较o1和o2的大小:
- 如果方法返回正整数,则表示o1大于o2;
- 如果返回0,表示相等;
- 返回负整数,表示o1小于o2。
3.2 代码举例:
Comparator com = new Comparator() {
//指明商品比较大小的方式:照产品名称从低到高排序,再照价格从高到低排序
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof Goods && o2 instanceof Goods){
Goods g1 = (Goods)o1;
Goods g2 = (Goods)o2;
if(g1.getName().equals(g2.getName())){
return -Double.compare(g1.getPrice(),g2.getPrice());
}else{
return g1.getName().compareTo(g2.getName());
}
}
throw new RuntimeException("输入的数据类型不一致");
}
}
4. 两种排序方式对比
- Comparable接口的方式是一定的,保证Comparable接口实现类的对象在任何位置都可以比较大小。
- Comparator接口属于临时性的比较。