1. 字符串相关的类
String类及其用法
字符串常量池的位置:
- jdk6之前:方法区(永久代)
- jdk7:堆
- jdk8:方法区(元空间)
package org.example;
import org.junit.Test;
/**
* String的使用
*
* @author AmorFati
* @create 2020/10/15 16:26
*/
public class StringTest {
/*
String:字符串,使用一对""引起来表示。
1. String声明为final的,不可被继承
2. String实现了Serializable接口:表示字符串是支持序列化的。
String实现了Comparable接口,表示String可以比较大小
3. String在内部定义了final char[] value用于存储字符串数据
4. String:代表一个不可变的字符序列。简称:不可变性。(非常重要)
-->体现:1. 当对字符串重新赋值时,需要重写指定内存区域赋值,不能使用原有的value进行赋值。
-->体现:2. 当对现有的字符串进行连接操作时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值。
-->体现:3. 当调用String的replace()方法修改指定字符或字符串时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值。
5. 通过字面量的方式(区别于new String())给一个字符串赋值,此时的字符串值声明在字符串常量池中。(非常重要)
6. 字符串常量池是不会存在相同内容的字符串的。
*/
@Test
public void test1() {
String s1 = "abc";//字面量的定义方式
String s2 = "abc";
System.out.println(s1 == s2);//比较s1和s2的地址值:true
s1 = "hello";
System.out.println(s1);//hello
System.out.println(s2);//abc
String s3 = "abc";
s3 += "def";
System.out.println(s3);//abcdef
System.out.println(s2);//abc
System.out.println("********");
String s4 = "abc";
String s5 = s4.replace('a', 'm');
System.out.println(s4);//abc
System.out.println(s5);//mbc
}
/*
String的实例化方式:
方式一:通过字面量定义的方式
方式二:通过new + 构造器的方式
面试题:String s = new String("abc");方式创建对象,在内存中创建了几个对象?
回答:两个。一个是堆空间中new结构,另一个是char[]对应的常量池中的数据:"abc"
*/
@Test
public void test2() {
//通过字面量定义的方式:此时的s1和s2的数据声明在方法区中的字符串常量池中。
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(s3 == s4);//false
System.out.println("***************");
Person p1 = new Person("Tom", 12);
Person p2 = new Person("Tom", 12);
System.out.println(p1.name.equals(p2.name));//true
System.out.println(p1.name == p2.name);//true
p1.name = "Jerry";
System.out.println(p2.name);//Tom
}
/*
结论:
1. 常量与常量的拼接结果在常量池中,且常量池中不会存在相同内容的常量。
2. 只要其中有一个是变量,结果就在堆中。
3. 如果拼接的结果调用intern()方法,返回值就在常量池中。
*/
@Test
public void test3() {
String s1 = "javaEE";
String s2 = "hadoop";
String s3 = "javaEEhadoop";
String s4 = "javaEE" + "hadoop"; //无变量在常量池中
String s5 = s1 + "hadoop";//有变量相当于new
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(s5 == s6);//false
System.out.println(s3 == s7);//false
System.out.println(s5 == s7);//false
System.out.println(s6 == s7);//false
String s8 = s5. intern();//返回值得到的s8使用的常量值中已经存在的“javaEEhadoop”
System.out.println(s3 == s8);//true
}
}
String常用方法
String 与byte[] 或char[]的转换
package org.example;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
/**
* @author AmorFati
* @create 2020/10/18 16:02
*/
public class StringTest1 {
/*
String 和char[] 之间的转换
*/
@Test
public void test1() {
String str1 = "abc123";
char[] charArray = str1.toCharArray();
for (char c : charArray) {
System.out.print(c);
}
System.out.println();
String str2 = new String(charArray);
System.out.println(str2);
}
/*
String和byte[]之间的转换
编码:String --> byte[]:调用String对象的getBytes()
解码:byte[]--> String:调用String对象的构造器
编码:字符串-->字节(看得懂的-->看不懂的二进制数据)
解码:编码的逆过程。字节-->字符串(看不懂的二进制数据-->看得懂的)
*/
@Test
public void test2() throws UnsupportedEncodingException {
String str1 = "abc123中国";
byte[] byteArray = str1.getBytes();//使用默认的字符集,进行转换
System.out.println(Arrays.toString(byteArray));
byte[] gbks = str1.getBytes("gbk");
System.out.println(Arrays.toString(gbks));
String str2 = new String(byteArray);
System.out.println(str2);
}
}
StringBuffer、StiringBuilder
package org.example;
import org.junit.Test;
/**
* @author AmorFati
* @create 2020/10/18 16:27
*/
public class StringBufferBuilderTest {
/*
String StringBuffer StringBuilder的异同?
String: 不可变的字符序列;底层结构使用char[]存储;
StringBuffer: 可变的字符序列;线程安全,效率低;底层结构使用char[]存储;
StringBuilder: 可变的字符序列;jdk5.0新增,线程不安全的,效率高;底层结构使用char[]存储;
源码分析:
String str = new String(); //new char[0];
String str1 = new String("abc"); //new char[]{'a','b','c'};
StringBuffer sb1 = new StringBuffer();//new char[16];底层创建了一个长度为16的数组
sb1.append('a');//value[0] = 'a';
sb2.append('b');//value[1] = 'b';
StringBuffer sb2 = new StringBuffer("abc");//new char["abc".length()+16];
//问题一:System.out.println(sb2.length());//3
//问题二:扩容问题:如果要添加的数据底层数组盛不下了,扩容底层的数组。
默认情况下,扩容为原来容量的2倍+2,同时将原有数组中的元素复制到新的数组中。
指导意义:开发中建议大家使用StringBuffer sb = new StringBuffer(int capacity);
或StringBuilder sb2 = new StringBuilder(int capacity);
常用方法:
增: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()
效率从高到低:StingBuilder、StringBuffer、String
*/
@Test
public void test1() {
StringBuffer sb1 = new StringBuffer("abc");
sb1.setCharAt(0, 'm');
System.out.println(sb1);//mbc,证明可变
System.out.println(sb1.length());
}
}
常用方法
注意
@Test
public void test4() {
String str = null;
StringBuffer sb = new StringBuffer();
sb.append(str);
System.out.println(sb.length());//4
System.out.println(sb);//"null"
StringBuffer sb1 = new StringBuffer(str);//java.lang.NullPointerException
System.out.println(sb1.length());
System.out.println(sb1);
}
2. JDK8之前的日期时间API
System 静态方法
Date类
/*
java.util.Date类
|---java.sql.Date类
1.两个构造器
>Date date1 = new Date();
>Date date2 = new Date(long date);
2.两个方法的使用
>toString():显示当前的年、月、日、时、分、秒
>getTime(): 获取当前Date对象对应的毫秒数。
3. java.sql.Date对应着数据库中的日期类型的变量
>如何实例化 Date date3 = new Date(long date);
>如何将一个java.util.Date对象转化成为java.sql.Date对象?
java.sql.Date date5 = new java.sql.Date(date4.getTime());
*/
@Test
public void test2() {
//构造器1:Date():创建一个对应当前时间的Date对象
Date date1 = new Date();
System.out.println(date1.toString());//Sun Oct 18 17:13:22 CST 2020
System.out.println(date1.getTime());//1603012429623
//构造器2:创建指定毫秒数的Date对象
Date date2 = new Date(1603012429623L);
System.out.println(date2.toString());
java.sql.Date date3 = new java.sql.Date(1603012429623L);
System.out.println(date3);//2020-10-18
Date date4 = new Date();
java.sql.Date date5 = new java.sql.Date(date4.getTime());
System.out.println(date5);
}
java.text.SimpleDateFormat类
/*
SimpleDateFormat的使用:对日期Date类的格式化和解析
1.两个操作:
1.1 格式化:日期--->字符串
1.2 解析:格式化的逆过程,字符串--->日期
2. 实例化
*/
@Test
public void test3() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat();
//格式化:
Date date = new Date();
System.out.println(date);
String format = sdf.format(date);
System.out.println(format);
//解析
String str = "20-10-19 上午10:42";
Date date1 = sdf.parse(str);
System.out.println(date1);
//**********************************
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");
//格式化
Date date2 = new Date();
String format1 = sdf1.format(date2);
System.out.println(format1);
//解析:要求字符串必须时符合SimpleDateFormat识别的格式(通过构造器参数体现)
//否则,抛异常
Date date3 = sdf1.parse("2020.10.19 10:48:11");
System.out.println(date3);
}
/*
练习一:字符串“2020-09-08”转换为java.sql.Date
*/
@Test
public void test4() throws ParseException {
String birth = "2020-09-08";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf1.parse(birth);
java.sql.Date birthDate = new java.sql.Date(date.getTime());
System.out.println(birthDate);
}
Calendar类
3. JDK8中新日期时间API
LocalDate、LocalTime、LocalDateTime
/*
LocalDate LocalTime LocalDateTime
*/
@Test
public void test1() {
//now(): 获取当前的日期、时间、日期+时间
LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDate);
System.out.println(localTime);
System.out.println(localDateTime);
//of(): 设置指定的年、月、日、时、分、秒。没有偏移量
LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 19, 14, 49, 33);
System.out.println(localDateTime1);
//getXxx()
System.out.println(localDateTime.getDayOfMonth());
System.out.println(localDateTime.getDayOfWeek());
//withXxx() 设置。体现不可变性
LocalDateTime localDateTime2 = localDateTime.withDayOfMonth(22);
System.out.println(localDateTime);//2020-10-19T14:52:23.087
System.out.println(localDateTime2);//2020-10-22T14:52:23.087
//plusXxx() 加
LocalDateTime localDateTime3 = localDateTime.plusMonths(2);
System.out.println(localDateTime);
System.out.println(localDateTime3);
//minusXxx() 减
LocalDateTime localDateTime4 = localDateTime.minusHours(10);
System.out.println(localDateTime);
System.out.println(localDateTime4);
}
Instant
/*
Instant的使用
*/
@Test
public void testInstant() {
//now():获取本初子午线对应的标准时间
Instant instant = Instant.now();
System.out.println(instant);
//添加时间的偏移量
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime);
//获取对应的毫秒数(自1970年1月1日0分0秒(UTC)起的毫秒数
long milli = instant.toEpochMilli();
System.out.println(milli);
//ofEpochMilli()
Instant instant1 = Instant.ofEpochMilli(23242L);
System.out.println(instant1);
}
DateTimeFormatter
/*
DateTimeFormatter:格式化或解析日期、时间
类似于SimpleDateFormat
*/
@Test
public void testDateTimeFormatter() {
//方式一:预定义的标准格式。
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
//格式化
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);//2020-10-19T15:11:20.693
String format = formatter.format(localDateTime);
System.out.println(format);//2020-10-19T15:11:20.693
//解析
TemporalAccessor parse = formatter.parse("2020-10-19T15:11:20.693");
System.out.println(parse);
/*
方式二:本地化相关的格式。如:ofLocalizedDateTime()
FormatStyle.SHORT FormatStyle.MEDIUM FormatStyle.LONG
*/
DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
String format1 = formatter1.format(localDateTime);
System.out.println(format1);
//方式三:自定义的格式。如:ofPattern("yyyy-MM-dd hh:mm:ss")
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
//格式化
String format2 = formatter2.format(localDateTime);
System.out.println(format2);
//解析
TemporalAccessor parse1 = formatter2.parse("2020-10-19 03:20:50");
System.out.println(parse1);
}
其他类
4. Java比较器
Comparable接口
/*
Comparable接口的使用举例
1. 像String、包装类等实现了Comparable接口,重写了CompareTo()方法,给出了比较两个对象的大小方法。
2. 像String、包装类重写了compareTo()方法以后,进行了从小到大的排序
3. 重写compareTo(obj)的规则:
如果当前对象this大于形参对象obj, 则返回正整数
如果当前对象this小于形参对象obj, 则返回负整数
如果当前对象this等于形参对象obj, 则返回零。
4. 如果自定义类需要排序,让自定义类实现Comparable接口,重写compareTo()方法
*/
@Test
public void TestComparable() {
String[] arr = new String[]{"AA", "MM", "GG","DD"};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
@Test
public void TestComparable2() {
Goods[] arr = new Goods[4];
arr[0] = new Goods("lenovoMouse", 34);
arr[1] = new Goods("huaweiMouse", 43);
arr[2] = new Goods("appleMouse", 12);
arr[3] = new Goods("xiaomiMouse", 66);
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
public class Goods implements Comparable<Goods>{
private String name;
private int price;
public Goods(String name, int price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Goods{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
@Override
public int compareTo(Goods o) {
return Integer.compare(this.price, o.price);
}
}
Comparator接口
/*
Comparator接口的使用:定制排序
1.背景:当元素的类型没有实现Comparable接口而又不方便修改代码
或实现了Comparable接口但排序规则不适合当前的操作
那么可以考虑使用Comparator的对象来排序。
2. 重写compare(obj1, obj2)方法,比较obj1和obj2的大小
*/
@Test
public void testComparator() {
String[] arr = new String[]{"AA", "MM", "GG","DD"};
Arrays.sort(arr, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return -o1.compareTo(o2);
}
});
System.out.println(Arrays.toString(arr));
}
5. System类