一、java.lang.String类的使用
1.概述
string类:代表字符串。Java程序中的所有字符串字面值都作为此类的实例实现
String是一个final类,代表不可变的字符序列
字符串是常量,用双引号引起来表示,他们的值在创建之后不可更改
String对象的字符内容是存储在一个字符数组value[]中的
String:字符串,使用一对""引起来表示 1.String声明为final的,不可以被继承 2.String实现了Serializable接口:表示字符串是支持序列化的 实现了Comparable接口:表示String可以比较大小 3.String内部定义了final char[] value字符数组用于存储字符串数据 4.String代表不可变的字符序列,简称:不可变性 5.通过字面量的方式(区别于new)给一个字符串赋值,此时的字符串值声明在字符串常量池中 6.字符串常量池中是不会存储相同内容的字符串的
2.不可变性
2.1说明
体现1:当对字符串重新赋值时,需要重新指定内存区域赋值,不能使用原有的value进行赋值 体现2:当对现有的字符串进行连接操作时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值 体现3:当调用String的replace()方法修改指定字符或字符串时,也需要重新指定内存区域赋值,不能使用原有 的value进行赋值
2.2代码举例
public void test1(){
String s1 = "abc";
String s2 = "abc";
System.out.println(s1 == s2);//比较s1和s2的地址值
s1 = "hello";
System.out.println(s1);//hello
System.out.println(s2);//abc
System.out.println("***********");
String s3 = "bac";
s3 += "def";
System.out.println(s3);//abcdef
System.out.println(s2);
System.out.println("***********");
String s4 = "abc";
String s5 = s4.replace('a', 'm');
System.out.println(s4);//abc
System.out.println(s5);//mbc
}
3.String实例化的不同方式
3.1方式说明
方式一:通过字面量定义的方式 方式二:通过new + 构造器的方式
3.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
3.3面试题
String s = new String("abc");方式创建对象?在内存中创建了几个对象? 两个:一个是堆空间new结构,另一个是char[]对应的常量池中的数据:"abc"
4.字符串拼接方式赋值的对比
4.1说明
1.常量与常量拼接的结果在常量池,且常量池中不会存在相同内容的常量 2.只要其中有一个是变量,其结果就在堆中 3.如果拼接的结果调用intern()方法,返回值就在常量池中
4.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 = s5.intern();//返回值得到的s8使用的常量值是已经存在的javaEEhadoop
System.out.println(s3 == s8);//true
********************************************
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;
5.常用方法
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 equalsIgnoreCast(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 toffset):测试此字符串是否以指定的前缀结束 boolean startsWith(String suffix,int toffset):测试此字符串从指定索引开始的子字符串是否 boolean contains(CharSequence s):当且仅当此字符串包含指定的char值序列时,返回true int indexOf(String str):返回指定子字符串在此字符串第一次出现处的索引 int indexOf(String str,int formIndex):返回指定子字符串在此字符串第一次出现处的索引 int lastIndexOf(String str):返回指定子字符串在此字符串中最右边出现处的索引 int lastIndexOf(String str,int formIndex):返回指定子字符串在此字符串中最右边出现处的索引 注:indexOf和lastIndexOf方法如果未找到都是返回-1 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个 如果超过了,剩下的全部都放到最后一个元素中
6.String与去他结构之间的转换
6.1与基本数据类型、包装类之间的转换
String-->基本数据类型,包装类:调用包装类的静态方法:parseXxx(str) 基本数据类型,包装类-->String:调用String重载的valueOf(xxx)
public void test(){
String str1 = "123";
// int num = (int)str1;//错误的
int num = Integer.parseInt(str1);
String str2 = String.valueOf(num);
String str3 = num + "";
System.out.println(str1 == str3);
}
6.2与字符数组之间的转换
String --> char[]:调用String的toCharArray() char[] --> String:调用String的构造器
public void test2(){
String str1 = "abc123";
char[] charArray = str1.toCharArray();
for (int i = 0; i < str1.length(); i++) {
System.out.println(charArray[i]);
}
char[] arr2 = new char[]{'h','e','l','l','o'};
String str2 = new String(arr2);
System.out.println(str2);
}
6.3与字节数组之间的转换
String 与 byte[]之间的转换 编码:String --> byte[]:调用String的getBytes() 解码:byte[] --> String: 编码:字符串 --> 字节(看得懂 --> 看不懂的二进制数据) 解码:字节 --> 字符串( 看不懂的二进制数据 --> 看得懂) 说明:解码时,要求解码使用的字符集必须与编码使用的字符集一致,否则会出现乱码
public void test3() throws UnsupportedEncodingException {
String str1 = "abc123中国";
byte[] bytes = str1.getBytes();//使用默认的字符集进行编码
System.out.println(Arrays.toString(bytes));//使用gbk字符集进行编码
byte[] gbks = str1.getBytes("gbk");
System.out.println(Arrays.toString(gbks));
System.out.println("*********************");
String str2 = new String(bytes);//使用默认的字符集进行解码
System.out.println(str2);
String str3 = new String(gbks);
System.out.println(str3);//出现乱码,原因:编码集和解码集不一样
String str4 = new String(gbks, "gbk");
System.out.println(str4);//没有出现乱码,原因:编码集和解码集一样
}
6.4与StringBuffer、StringBuilder之间的转换
String --> StringBuffer、StringBuilder:调用StringBuffer、StringBuilder构造器 StringBuffer、StringBuilder --> String:①调用String构造器 ②StringBuffer、StringBuilder的toString()方法
7..JVM字符串常量池存放位置说明
jdk 1.6(jdk 6.0 ,java 6.0):字符串常量池存储在方法区(永久区) jdk 1.7:字符串常量池存储在堆空间 jdk 1.8:字符串常量池存储在方法区(元空间)
二.String 、 StringBuffer、StringBuilder三者的对比
String:不可变的字符序列,底层使用char[]数组存储 StringBuffer:可变的字符系列:线程安全的,效率低,底层使用char[]数组存储 StringBuilder:可变字符序列:jdk5.0新增的,线程不安全的,效率低,底层使用char[]数组存储
8.1StringBuffer与StringBuilder的内存解析
以StringBuffer为例: String str = new String();new char[0]; String str1 = new String(abc);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]; 问题一:System.out.println(sb2.length());//3 问题二:如果要添加的数据底层数组盛不下了,那就需要扩容底层的数组 默认情况下,扩容为原来容量的2倍 + 2;同时将原有数组中的元素复制到新的数字中 指导意义:开发中建议大家使用:StringBuffer(int capacity)或StringBuilder(int capacity)
8.2 对比String 、 StringBuffer、StringBuilder三者的执行效率
从高到低排列:StringBuffer > StringBuild > String
8.3 StringBuffer、StringBuilder中的常用方法
增:append(xxx) 删: delete(int start,int end) 改: setCharAt(int n,char ch)/ replace(int start,int end,String str) 查: charaAt(int n) 插: insert(int offset,xxx) 长度:length() 遍历:for() + charAt()
9-2JDK8之前日期时间API
1.获取系统当前时间
System类中的currentTimesMills()
long time = System.currentTimeMillis(); //返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差 //称为时间戳 System.out.println(time);
2.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对象
//System类中的currentTimesMills()
public void test1(){
long time = System.currentTimeMillis();
//返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差
//称为时间戳
System.out.println(time);
}
public void test2(){
//构造器一:Date();创建一个对应当前时间的Date对象
Date date1 = new Date();
System.out.println(date1.toString());//Tue Oct 04 20:39:52 CST 2022
System.out.println(date1.getTime());//1664887192616
//构造器二:创建指定毫秒数的Date对象
Date date2 = new Date(1664887192616L);
System.out.println(date2.toString());//Tue Oct 04 20:39:52 CST 2022
//构造器三:创建java.sql.Date对象
java.sql.Date date3 = new java.sql.Date(1664887192616L);
System.out.println(date3);//2022-10-04
//构造器四:如何将java.util.Date对象转换为java.sql.Date对象
// Date date4 = new java.sql.Date(1664887192616L);
// java.sql.Date date5 = (java.sql.Date) date4;
//情况二:
Date date6 = new Date();
java.sql.Date date7 = new java.sql.Date(date6.getTime());
}
3.java.text.SimpleDateFormat类
SimpleDateFormat对日期Date的格式化和解析
1.两个操作 1.1 格式化:日期 --> 字符串 1.2 解析:格式化的逆过程: 字符串 ———> 日期 2.SimpleDateFormat类的实例化:new + 构造器
练习
//按照指定的方式格式化和解析:调用带参的构造器 // SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //格式化 String format1 = sdf1.format(date); System.out.println(format1); //解析 Date date2 = sdf1.parse("2022-10-06;09;09-42"); System.out.println(date2);
练习一:字符串"2022-10-6"转换为java.sql.Date 练习二:"三天打鱼两天晒网" 1990-01-01 xxxx-xx-xx 打渔? 晒网? 举例:2022-10-06?总天数? 总天数 % 5 = 1,2,3 打渔 总天数 % 5 = 4, 0 晒网 总天数的计算? 方式一:(date2.getTime() - date1.getTime()) / (1000 * 60 * 60 *24) + 1 方式二:1990-01-01 ——> 2021-12-31 + 2022-01-01 ——> 2022-10-06 public void testExer() throws ParseException { String birth = "2022-10-6"; SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf1.parse(birth); // System.out.println(date); java.sql.Date birthDate = new java.sql.Date(date.getTime()); System.out.println(birthDate); }
4.Calender类
1.日历类、抽象类
2.实例化 方式一:创建其子类(GregorianCalendar)的对象 方式二:调用其静态方法getInstance()
public void testCalendar(){ /* 1.实例化 方式一:创建其子类(GregorianCalendar)的对象 方式二:调用其静态方法getInstance() */ Calendar calendar = Calendar.getInstance(); // System.out.println(calendar); //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.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 date1 = new Date(); calendar.setTime(date1); days = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(days); }
9-3.Java中新日期时间API
1.日期时间API的迭代
第一代: jdk 1.0 Date类 第二代:jdk 1.1 Calendar类 ,一定程度上替换Date类 第三代:jdk 1.8 提出了一套新的API
2.前两代存在的问题举例
可变性:像日期和时间这样的类应该是不可变的 偏移性:Date中的年份是从1900年开始的,月份都从0开始 格式化:格式化只对Date用,Calen则不行 此外,他们也不是线程安全的;不能处理闰秒等
3.Java 8 中新的日期时间API涉及到的包
java.time: 包含值对象的基础包 java.time.chrono: 提供对不同的日历系统的访问 java.time.format:格式化和解析日期和时间 java.time.temporal: 包含底层框架和扩展特性 java.time.zone: 包含时区支持的类
4.本地日期、本地时间、本地日期时间的使用:LocalDate、LocalTime、LocalDateTime
4.1.说明
① 分别表示ISO-8601日历系统的时间、时间、时间和日期。它们提供了简单的本地日期或时间、并不包含当前的时间信 息,也不包含与时区相关的信息 ② localDateTime相较于localDate,localTime使用频率要高 ③ 类似于Calendar
4.2.常用方法
//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(2022, 10, 8, 20, 29, 54); System.out.println(localDateTime1);//2022-10-08T20:29:54 //getXxx():获取相关的属性 System.out.println(localDateTime.getDayOfMonth()); System.out.println(localDateTime.getDayOfWeek()); System.out.println(localDateTime.getMonth()); System.out.println(localDateTime.getMonthValue()); System.out.println(localDateTime.getMinute()); //体现不可变性 //getXxx():设置相关的属相 LocalDate localDate1 = localDate.withDayOfMonth(22); System.out.println(localDate);//2022-10-08 System.out.println(localDate1);//2022-10-22 LocalDateTime localDateTime2 = localDateTime.withHour(5); System.out.println(localDateTime);//2022-10-08T20:45:27.938 System.out.println(localDateTime2);//2022-10-08T05:45:27.938
5.时间点:Instant
说明: ①时间线上的一个瞬时点。概念上讲,他只是简单的表示自1970年1月1日0时0分0秒(UTC开始的秒数) ②类似于java.util.Date类
常用方法 //now():获取本初子午线对应的标准时间 Instant instant = Instant.now(); System.out.println(instant);//2022-10-08T13:06:13.901Z //田间时间的偏移量 OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8)); System.out.println(offsetDateTime);//2022-10-08T21:06:13.901+08:00 //toEpochMilli():获取子1970年1月1日0时0分0秒(UTC)开始的毫秒数 long milli = instant.toEpochMilli(); System.out.println(milli); Instant instant1 = Instant.ofEpochMilli(1665234769526L); System.out.println(instant1);
时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数
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:ss:mm") ②常用方法 ofPattern(String pattern):静态方法,返回一个指定字符串格式的DateTimeFormatter format(TemporalAccessort):格式化一个日期、时间,返回字符串 parse(CahrSequence):将指定格式的字符序列解析为一个日期、时间
特别的:自定义的格式,如:ofPattern("yyyy-MM-dd hh:ss:mm")
DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:ss:mm"); //格式化 String str4 = formatter3.format(localDateTime.now()); System.out.println(str4); //解析 TemporalAccessor accessor = formatter3.parse("2022-10-10 09:02:06"); System.out.println(accessor);
9-4.Java比较器
1.Java比较器的使用背景
java中的对象,正常情况下,只能进行比较:== 或 != 。不能使用 > 或 <,但在开发场景中,我们需要对多个对象进行排序, 言外之意,就需要比较对象的大小,如何实现,使用两个接口中的任何一个:Comparable 或 Comparator
2.Comparable接口的使用:自然排序
2.1说明
1.像String、包装类等实现了Comparable接口,重写了compareTo(obj)方法,给出了比较两个对象大小的方式 2.像String、包装类重写CompareTo()方法以后,进行了从小到大的排列 3.重写CompareTo(obj)的规则 如果当前对象this大于形参对象obj,则返回正整数 如果当前对象this等于形参对象obj,则返回0 如果当前对象this小于形参对象obj,则返回负整数 4.对于自定义类来说,如果需要排序,我们可以让自定义类实现Comparable接口,重写compareTo(obj)方法, compareTo(obj) 方法中指明如何排序
2.2代码举例
public class Goods implements Comparable{
private String name;
private double price;
public Goods() {
}
public Goods(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Goods{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
//指明商品比较大小的方式::按照价格从低到高排序
@Override
public int compareTo(Object o) {
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("传入的书路类型不一致!");
}
}
3.Comparable接口的使用:定制排序
3.1说明
1.背景 当元素的类型没有实现java.lang.Comparable接口而又不方便修改代码,或者实现了java.lang.Comparable接口的 排序规则不适合当前的操作,那么可以考虑使用Comparable的对象来排序 2.重写Comparable(Object o1,Object o2)的方法,比较o1和o2的大小 如果方法返回正整数,则表示o1大于o2; 如果方法返回0,则表示相等; 如果方法返回负整数,则表示o1小于o2;
3.2代码举例
public void test3() {
String[] arr = new String[]{"AA", "CC", "MM", "GG", "JJ", "DD"};
Arrays.sort(arr, new Comparator() {
//按照字符串从大到小的顺序排序
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof String && o2 instanceof String) {
String s1 = (String) o1;
String s2 = (String) o2;
return -s1.compareTo(s2);
}
// return 0;
throw new RuntimeException("输入的数据类型不一致");
}
});
System.out.println(Arrays.toString(arr));
}
@Test
public void test4() {
Goods[] arr = new Goods[6];
arr[0] = new Goods("lenovoMouse", 34);
arr[1] = new Goods("dellMouse", 43);
arr[2] = new Goods("xiaomiMouse", 12);
arr[3] = new Goods("huaweiMouse", 65);
arr[4] = new Goods("huaweiMouse", 224);
arr[5] = new Goods("microsoftMouse", 43);
Arrays.sort(arr, 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("输入的数据类型不一致");
}
});
System.out.println(Arrays.toString(arr));
}
}
使用 Arrays.sort(goods,com) Collection.sort(coll,com) new TreeSet(com)
4.两种排序方式对比
Comparable接口的方式一旦一定,保证Comparable接口实现类的对象在任何位置都可以比较大小 Comparator接口属于临时性的比较
9-5其他类
1.System类
① System类代表系统,系统级的很多属性和控制方法都放置在该类的内部,该类位于java.lang包。 ② 由于该类的构造器时private,所以无法创建该类的对象,也就是无法实例化该类。其内部的成员变量和成员方法都是 static,所以也可以很方便地进行调用 ③ 方法 native long currentTimeMillis() void exit() void gc() String getProperty(String key)
2.Math类
java.lang.Math提供了一系列静态方法用于科学计算,其方法的参数和返回值类型一般为double型
3.BigInteger 类和 BigDecimal类
① java.Math包的BigInteger 可以表示不可变的任意精度的整数 ② 要求数字精度比较高,用到java.Math.BigDecimal类