String 字符串的不可变性
String:字符串,使用一对 “” 引起使用
String 声明成 final 的,不能被继承
String 实现了 Serializable 接口,表示字符串可以实现序列化
String 实现了 Comparable 接口,表示字符串可以实现比较
String 内部定义了 private final char value[]; 用来存储字符串数据
String 代表不可变的字符序列。简称:不可变性
当对字符串重新赋值时,需要重写指定内存区域赋值,不能使用原有的value进行赋值
当对现有字符串进行连接操作时,也需要重新指定内存区域赋值,不能使用原有的值进行赋值
当调用 String 字符串的 replace 方法进行替换时,也需要重新指定内存区域进行赋值
通过字面量的方式(=赋值)(区别于new赋值)给定一个字符串赋值时,此时的字符串值声明在字面量常量池中
字符串常量池中是不会存储相同的字符串的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
String s1 = "abc"; String s2 = "123";
s1 = "def"; System.out.println(s1 == s2);
String s3 = s1; s3 += "123"; System.out.println(s1); System.out.println(s3);
String s4 = "hello"; String s5 = s4.replace("he", "He"); System.out.println(s4); System.out.println(s5);
|
String 不同实例化方式的对比
创建字符串的两种方式
- 字面量的方式创建字符串
String s1 = "javaEE";
- 通过
new + 构造器
的方式创建字符串 String s2 = new String("javaEE");
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
| class Person{ String name;
public Person(String name) { this.name = name; } } public class StringTest2 { @Test public void show(){ String s1 = "JavaEE"; String s2 = "JavaEE";
String s3 = new String("JavaEE"); String s4 = new String("JavaEE");
System.out.println(s1 == s2); System.out.println(s1 == s3); System.out.println(s3 == s4); System.out.println(s1.equals(s3));
Person p1 = new Person("Tome"); Person p2 = new Person("Tome"); p1.name = "Jory"; System.out.println(p1.name == p2.name);
} }
|
面试题:String s = new String("abc");
方式创建字符串在内存中创建了几个对象?
答:两个。一个是在堆空间中的 new 结构,另一个是 char[] 在常量池中的数据 abc
String 不同拼接操作
- 常量和常量拼接,结果还在常量池中,常量池中不会存在相同的数据
- 只要其中一个变量,那么结果就会在堆空间中,每创建一个用变量拼接的字符串,就会在堆空间中重新开辟一个空间
- 字符串调用 intern 方法,返回值就在常量池中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| String s1 = "HelloWorld"; String s2 = "Hello" + "World"; String s3 = "Hello"; String s4 = "World"; String s5 = s3 + "World"; String s6 = "Hello" + s4; String s7 = s3 + s4; String s8 = s3 + s4;
System.out.println(s1 == s2); System.out.println(s1 == s5); System.out.println(s1 == s7); System.out.println(s5 == s6); System.out.println(s5 == s7); System.out.println(s8 == s7);
String s9 = s8.intern(); System.out.println(s1 == s9);
|
解决一个拼接问题
1 2 3 4 5 6 7 8 9
| String s1 = "HelloWorld"; String s2 = "Hello"; String s3 = s2 + "World"; System.out.println(s1 == s3);
final String s4 = "Hello"; String s6 = s4 + "World"; System.out.println(s1 == s6);
|
String 类型的值传递问题解析
先看代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
public class StringTest3 { String str = new String("Good"); char[] ch = new char[]{'t','e','s','t'};
public void change(String str,char[] ch){ str = "hello"; ch[0] = 'b'; } @Test public void show(){ StringTest3 s = new StringTest3(); s.change(s.str, s.ch); System.out.println(s.str); System.out.println(s.ch); } }
|
当传递的参数数据是String类型是,方法修改传递过来的形参值,实参的值不会跟着改变,因为String字符串是不可变性,和引用数类型不同,引用数据类型的数据指向的是地址值,只要修改了引用数据类型的数据,所有指向这个地址的数据都会跟着修改
1 2 3 4 5 6 7 8 9 10 11 12
| String name = new String("张三"); public void test(String name){ name = "李四"; System.out.println(name); } @Test public void show2(){ StringTest3 s = new StringTest3(); s.test(s.name); System.out.println(name); }
|
String 类常用方法1
- 1.获取字符串的长度 int length()
- 2.返回某索引处的字符 char charAt()
- 3.判断字符串是否是空 boolean isEmpty()
- 4.将字符串转为小写 string toLowerCase()
- 5.将字符串转为大写 string toUpperCase()
- 6.忽略字符串中的前后空白 string trim()
- 7.比较字符串是否相同 Boolean equals()
- 8.忽略大小写的情况下比较两个字符串是否相同 boolean equalsIgnoreCase()
- 9.链接字符串,和 + 作用相同 string concat()
- 10.比较两个字符串大小 int compareTo()
- 11.从下标为2的地方开始截取字符串,包含2下标,并返回新的字符串 string substring(int beginIndex)
- 12.从下标2截取到下标7,包含2不包含7,左闭右开 substring(int beginIndex,int endIndex)
- 13.返回某个字符在字符串中的下标,没有时返回-1 int indexOf()
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 47 48 49 50
| String s1 = "HelloWorld"; System.out.println(s1.length());
System.out.println(s1.charAt(5));
String s2 = ""; System.out.println(s1.isEmpty()); System.out.println(s2.isEmpty());
System.out.println(s1); System.out.println(s1.toLowerCase());
System.out.println(s1.toUpperCase());
String s3 = " Hel lo World "; System.out.println(s3.trim());
String s4 = "hello"; String s5 = "hello"; System.out.println(s4.equals(s5));
String s6 = "Hello"; System.out.println(s4.equalsIgnoreCase(s6));
String s7 = s6.concat("World"); System.out.println(s7);
String s8 = "abc"; String s9 = "def"; System.out.println(s8.compareTo(s9));
String s10 = "勇敢牛牛,不怕困难"; System.out.println(s10.substring(2));
System.out.println(s10.substring(2, 7));
System.out.println(s10.indexOf("牛"));
|
String 类常用方法2
- 1.判断字符串是否以某个字符串结尾 boolean endsWith()
- 2.判断字符串是否以某个字符开头 boolean startsWith()
- 3.从指定索引位置开始判断是否以某个字符串开头, boolean startsWith(String prefix,int toffset)
- 4.判断某个字符串中是否包含某个字符串 Boolean contains()
- 5.返回某个字符串在字符串中第一次出现的下标,不存在返回 -1; int indexOf()
- 6.返回某个字符串在字符串中最后一次出现的下标 int lastIndexOf()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| String s1 = "HelloWorld"; System.out.println(s1.endsWith("ld")); System.out.println(s1.endsWith("lds"));
System.out.println(s1.startsWith("He")); System.out.println(s1.startsWith("Hes"));
System.out.println(s1.startsWith("Wo", 5));
System.out.println(s1.contains("llo"));
System.out.println(s1.indexOf("lo"));
String s2 = "hello,hello";
System.out.println(s2.lastIndexOf("l"));
|
String 类常用方法3
- 1.将字符串中的某个字符全部替换为新的字符 string replace(oldChar,newChar)
- 2.replace() 方法也可以替换字符串中的某个字符串为新的字符串
- 3.将字符串中符合正则表达式的内容全部替换为新的内容 replaceAll(regex,replacement)
- 4.使用给定的正则表达式替换字符串中符合条件的第一个字符 replaceFirst(regex,replacement)
- 5.判断字符串是否符合某个正则表达式 boolean matches(regex)
- 6.将字符串按照某个正则分隔成字符串数组 String[] split(regex)
- 7.split 方法的第二个参数可以控制最多拆分几个,如果超过了,最后一个都放在最后一个元素中
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
| String s1 = "hello world"; String s2 = s1.replace('l', 'n'); System.out.println(s2);
String s3 = "我要去北京的北京故宫"; String s4 = s3.replace("北京", "南京"); System.out.println(s4);
String s5 = "+++123456---123456"; String s6 = s5.replaceAll("\\+", "-"); System.out.println(s6);
String s7 = s5.replaceFirst("\\+", "-"); System.out.println(s7);
String s8 = "songzx@qq.com"; System.out.println(s8.matches("\\w+@\\w+.\\w+"));
String s9 = "song,zheng,xinag"; String[] s10 = s9.split(","); for (int i = 0; i < s10.length; i++) { System.out.println(s10[i]); }
String[] s11 = s9.split(",", 2); for (int i = 0; i < s11.length; i++) { System.out.println(s11[i]); }
|
String 字符串和 char 数组转换
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
|
public class StringTest7 { @Test public void show() { String s1 = "hello"; char[] chars = s1.toCharArray(); for (int i = 0; i < chars.length; i++) { System.out.println(chars[i]); }
char[] newchars = new char[]{'a', 'b', 'c', 'd', 'e'}; String s2 = new String(newchars); System.out.println(s2);
String s3 = "ab123c"; char[] chars1 = s3.toCharArray(); char[] chars2 = new char[4]; for (int i = chars1.length - 2, j = 0; i >= 1 && j < 4; i--, j++) { System.out.println(chars1[i]); chars2[j] = chars1[i]; } String s4 = new String(chars2); String s5 = "a" + s4 + "c"; System.out.println(s5); } }
|
String 和 byte[] 字节数组转换
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
|
public class StringTest8 { @Test public void show() throws UnsupportedEncodingException { String s1 = "hello 中国"; byte[] bytes = s1.getBytes(); System.out.println(Arrays.toString(bytes));
byte[] gbks = s1.getBytes("gbk"); System.out.println(Arrays.toString(gbks));
String s2 = new String(bytes); System.out.println(s2);
String s3 = new String(gbks); System.out.println(s3); String s4 = new String(gbks, "gbk"); System.out.println(s4); } }
|
StringBuffer 源码分析
String、StringBuffer、StringBuilder三者的异同
- String:不可变的字符序列,底层用 char[] 存储,添加了 final 修饰符
- StringBuffer:可变的字符序列,线程安全的,效率低,底层用 char[] 存储
- StringBuilder:可变的字符序列,线程不安全的,效率高,底层用 char[] 存储
声明 String s1 = new String()
时底层会声明一个 char 型数组,每次声明一个 String,就会创建一个新的 char 型数组
1
| char[] value = new char[0];
|
声明 String s1 = new String("abc")
底层代码
1
| char[] value = new char[]{'a','b','c'};
|
声明 StringBuffer sb1 = new StringBuffer()
时底层的结构。底层创建了一个长度是16的char型数组
1 2 3
| char[] value = new char[16]; sb1.append("a"); sb1.append("b");
|
声明 StringBuffer s1 = new StringBuffer("abc")
底层代码,当StringBuffer 构造器默认有值时,会创建一个在默认字符串长度的基础上加16的长度的 char 数组
1
| char[] value = new char["abc".length() + 16];
|
问题一:StringBuffer s1 = new StringBuffer("abc")
这段代码中打印 s1.lenght
是多少
- 打印的长度为 3 ,因为底层不会返回 char 数组的长度,而是每次 append 之后 count++,返回的是字符串的个数
问题二:扩容问题:
- 如果需要添加的数据底层数组盛不下,那就需要扩容底层数组的长度,默认情况下扩容为原来的二倍并且加上2,同时将原有数组复制到新数组中
- 指导意义:开发中建议使用
StringBuffer s2 = new StringBuffer(20);
直接声明好字符串的长度,避免在使用中发生扩容情况
StringBuffer 常用方法
- 1.append() 在字符串结尾追加方法.可以增加任意类型的数据,添加后原始数据发生改变
- 2.delete 删除指定位置的字符,左闭右开
- 3.replace(start,end,str) 把 [2,6) 位置上的字符串替换为 你好
- 4.insert(offset,str) 在指定的下标处添加字符串
- 5.reverse() 反转字符串
- 6.int indexOf() 返回指定字符串的下标
- 7.String substring(start,end) 返回指定区间的字符串
- 8.charAt(int) 查找指定下标的元素值,并返回
- 9.setCharAt(index,char) 修改指定下标的元素
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
| StringBuffer s1 = new StringBuffer("hello");
s1.append("world"); s1.append(123); s1.append(false);
s1.delete(2,3);
s1.replace(2,6,"你好");
s1.insert(5,"世界");
s1.reverse();
int index = s1.indexOf("你"); System.out.println(index);
String s2 = s1.substring(2, 6); System.out.println(s2);
char c = s1.charAt(5); System.out.println(c);
s1.setCharAt(5,'a');
System.out.println(s1);
|
String 和 StringBuffer、StringBuilder 相互转换
1 2 3 4 5 6 7 8 9 10 11
| String s1 = "hello";
StringBuffer sb1 = new StringBuffer(s1);
StringBuffer sb2 = new StringBuffer("hello");
String s2 = new String(sb2);
String s3 = sb2.toString();
|
上面的代码只演示了String
和StringBuffer
之间相互转换的方法,String
和StringBuilder
之间转换方式与之相同
String、StringBuffer、StringBuilder三者效率对比
效率排行排序:
StringBuilder > StringBUffer > String
在不考虑线程安全的前提下,我们可以使用 StringBuilder
Java中两个Date类的使用
- 第一个Date是:
java.util.Date
- 第二个Date是:
java.sql.Date
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
| public class DateTest1 { @Test public void show(){ Date date1 = new Date(); System.out.println(date1); System.out.println(date1.getTime());
java.sql.Date date2 = new java.sql.Date(date1.getTime()); System.out.println(date2); System.out.println(date2.getTime());
Date d3 = new Date(); java.sql.Date d4 = new java.sql.Date(d3.getTime()); System.out.println(d4);
Date d5 = new java.sql.Date(1627887137692L); System.out.println(d5); System.out.println(d5.getTime()); } }
|
模拟 trim 方法,去除字符串两端空格
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
| @Test public void show() { String s1 = " hello world sss "; String s2 = myTrim(s1); System.out.println(s2); }
public String myTrim(String str) { char[] chars = str.toCharArray(); int leftIndex = 0; int rightIndex = 0; for (int i = 0; i < chars.length; i++) { if (chars[i] != ' ') { leftIndex = i; break; } } for (int i = chars.length - 1; i >= 0; i--) { if (chars[i] != ' ') { rightIndex = i; break; } } return str.substring(leftIndex, rightIndex + 1); }
|
翻转指定的字符串,例如:将 abcdefg 转成 afedcbg
方式一
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @Test public void show() { String s1 = "abcdefg"; String s2 = "a"; char[] chars = s1.substring(1, 6).toCharArray(); for (int i = chars.length - 1; i >= 0; i--) { s2 = s2 + chars[i]; } s2 += "g"; System.out.println(s2); }
|
方式二
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| @Test public void show2() { String s1 = "abcdefg"; String s2 = myResover(s1, 1, 6); System.out.println(s2); }
private String myResover(String s1, int startIndex, int endIndex) { StringBuilder sb1 = new StringBuilder(s1.length()); sb1.append(s1.substring(0, startIndex)); char[] chars = s1.substring(startIndex, endIndex).toCharArray(); for (int i = chars.length - 1; i >= 0; i--) { sb1.append(chars[i]); } sb1.append(s1.substring(endIndex)); return sb1.toString(); }
|
计算字符串中某个字符出现的次数
方式一:使用 replace 的方式计算字符串出现次数
1 2 3 4 5 6 7 8 9 10 11
| @Test public void show() { String s1 = "absdifhabiosdfiabsoidfabsdf"; String s2 = "ab"; int oldCount = s1.length(); int newCount = s1.replace(s2, "").length(); System.out.println((oldCount - newCount) / s2.length()); }
|
方式二:使用 while 循环加 indexOf
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
| @Test public void show2() { String s1 = "absdifhabiosdfiabsoidfabsdf"; String s2 = "ab"; int count = getStrCunt(s1, s2); System.out.println(count); }
private int getStrCunt(String mainStr, String subStr) { int count = 0; int index = 0; int mainStrLength = mainStr.length(); int subStrLength = subStr.length(); if (subStrLength > mainStrLength) return 0; while ((index = mainStr.indexOf(subStr, index)) != -1) { count++; index += subStrLength; } return count; }
|
获取两个字符串中最大相同子串
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
| @Test public void testGetSomeStr() { String a = "sffioafihellosdfvasdf"; String b = "sfhellodesdfs"; String c = getSomeStr(a, b); System.out.println(c); } public String getSomeStr(String str1, String str2) { String maxstr = str1; String minstr = str2; if (str2.length() > str1.length()) { maxstr = str2; minstr = str1; } int lunCount = minstr.length(); for (int i = 0; i < lunCount; i++) { for (int x = 0, y = lunCount - i; y <= lunCount; x++, y++) { if(maxstr.contains(minstr.substring(x,y))){ return minstr.substring(x,y); } } } return null; }
|
对字符串中字符进行按自然顺序排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Test public void show(){ String s1 = "qwertyasdfghzxcvbn"; String s2 = myStrSort(s1); System.out.println(s2); } public String myStrSort(String s){ char[] chars = s.toCharArray(); Arrays.sort(chars); String sortStr = new String(chars); return sortStr; }
|
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
| package com.songzx.java;
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date;
public class SimpleDateFormat1 { public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = sdf.format(new Date()); System.out.println(format);
try { Date date = sdf.parse("2021-08-03 14:19:48"); System.out.println(date); System.out.println(date.getTime()); } catch (ParseException e) { e.printStackTrace(); } } }
|
将 “2021-08-03 14:29:56” 转换成 java.sql.Date
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
| package com.songzx.java;
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date;
public class SimpleDateFormat2 { public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date date = sdf.parse("2021-08-03 14:29:56"); java.sql.Date date1 = new java.sql.Date(date.getTime());
System.out.println(date1); } catch (ParseException e) { e.printStackTrace(); }
} }
|
三天打鱼两天晒网,从1990-01-01 开始到之后的某一天,某一天从键盘输入,判断这一天是在打鱼还是在晒网
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| package com.songzx.java;
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner;
public class SimpleDateFormat3 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入年"); String yyyy = sc.next(); System.out.println("请输入月"); String MM = sc.next(); System.out.println("请输入日"); String dd = sc.next(); String startDate = "1990-01-01"; String endDate = yyyy + "-" + MM + "-" + dd; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { Date date1 = sdf.parse(startDate); Date date2 = sdf.parse(endDate); int diffday = (int) ((date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24) + 1); String result = getResult(diffday); System.out.println(result); } catch (ParseException e) { e.printStackTrace(); } }
private static String getResult(int diffday) { switch (diffday % 5){ case 1: case 2: case 3: return "打鱼"; case 4: case 0: return "晒网"; default: return null; } } }
|
Calender 日历类的常用方法
注意:
- 日历类中获取一月是0,十二月是11
- 日历类中获取周日是1,周六是7
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
| package com.songzx.java;
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date;
public class CalenderTest1 { public static void main(String[] args) throws ParseException { Calendar instance = Calendar.getInstance();
System.out.println(instance.get(Calendar.WEEK_OF_YEAR)); System.out.println(instance.get(Calendar.WEEK_OF_MONTH)); System.out.println(instance.get(Calendar.DAY_OF_MONTH)); System.out.println(instance.get(Calendar.DAY_OF_YEAR));
Date date = instance.getTime(); System.out.println(date);
String strdate = "2021-09-25"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date parse = sdf.parse(strdate); instance.setTime(parse); System.out.println(instance.get(Calendar.DAY_OF_YEAR)); } }
|
LocalDate、LocalTime、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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| package com.songzx.java;
import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime;
public class LocalDateTime1 { public static void main(String[] args) { LocalDate localDate = LocalDate.now(); LocalTime localTime = LocalTime.now(); LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDate); System.out.println(localTime); System.out.println(localDateTime);
LocalDate localDate1= LocalDate.of(2021, 5, 15); System.out.println(localDate1);
System.out.println(localDate.getDayOfMonth()); System.out.println(localDate.getDayOfWeek()); System.out.println(localDate.getMonthValue()); System.out.println(localDate.getDayOfYear());
LocalDate localDate2 = localDate.withDayOfMonth(16); System.out.println(localDate2); System.out.println(localDate);
LocalDate localDate3 = localDate.withMonth(5); System.out.println(localDate3);
LocalDate localDate4 = localDate.plusWeeks(5); System.out.println(localDate); System.out.println(localDate4);
LocalDate localDate5 = localDate.plusDays(3); System.out.println(localDate5);
LocalDate localDate6 = localDate.minusDays(10); System.out.println(localDate6);
LocalDate localDate7 = localDate.minusWeeks(1); System.out.println(localDate7);
} }
|
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 26 27 28 29 30 31 32 33 34 35
| package com.songzx.java;
import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.Date;
public class Instant1 { public static void main(String[] args) { Instant instant = Instant.now(); System.out.println(instant);
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8)); System.out.println(offsetDateTime);
long l = instant.toEpochMilli(); System.out.println(l);
Instant instant1 = Instant.ofEpochMilli(new Date().getTime()); Instant instant2 = Instant.ofEpochMilli(l); System.out.println(instant1); System.out.println(instant2);
} }
|
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 47 48 49 50 51 52 53 54
| package com.songzx.java;
import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle;
public class DateTimeFormatter1 { public static void main(String[] args) {
DateTimeFormatter date1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG); String format1 = date1.format(LocalDateTime.now()); System.out.println(format1);
DateTimeFormatter date2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL); String format2 = date2.format(LocalDate.now()); System.out.println(format2);
DateTimeFormatter date3 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String format3 = date3.format(LocalDateTime.now()); System.out.println(format3);
System.out.println(date3.parse("2021-08-04 15:54:47")); } }
|
Comparable(自然排序) 接口的使用
对于String类和一些常用类都已经实现了Comparable接口,所以可以直接使用sort方法来实现排序的功能
1 2 3 4 5 6 7
| public static void main(String[] args) { String[] strings = new String[]{"b","s","你好","dd","cnm","哈哈"};
Arrays.sort(strings); System.out.println(Arrays.toString(strings)); }
|
对于自定义类来说如果要实现排序功能,需要重写CompareTo方法,重写规则如下
- 如果当前对象this大于形参对象obj,则返回正整数
- 如果当前对象this小于形参对象obj,则返回负整数
- 如果相等则返回0
- 需要在 compareTo 方法中定义好排序规则
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| import java.util.Arrays;
class Goos implements Comparable { String name; double price;
public Goos() { }
public Goos(String name, double price) { this.name = name; this.price = price; }
@Override public String toString() { return "Goos{" + "name='" + name + '\'' + ", price=" + price + '}'; }
@Override public int compareTo(Object o) { if (o instanceof Goos) { Goos goos = (Goos) o; if(this.price > goos.price){ return 1; }else if(this.price < goos.price){ return -1; }else{ return 0; } } throw new RuntimeException(); } }
public class Comparable2 { public static void main(String[] args) { Goos[] goos = new Goos[4]; goos[0] = new Goos("leven", 12); goos[1] = new Goos("dell", 32); goos[2] = new Goos("xiaomi", 16); goos[3] = new Goos("huawei", 25); goos[4] = new Goos("phone", 19.9);
Arrays.sort(goos); System.out.println(Arrays.toString(goos)); } }
|
Comparator(定制排序)接口的使用
Comparable 和 Comparator 两者区别
相同点:
不同点:
- Comparable 接口需要重写 compareTo 方法
- Comparator 接口需要重写 compare 方法
- Comparable 接口定实现好重写完 compareTo 方法之后,接口的实现类在任何地方都可以进行比较
- Comparator 接口属于临时比较
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| package com.songzx.java;
import javax.management.RuntimeErrorException; import java.util.Arrays; import java.util.Comparator;
class Goods{ String name; double price;
public Goods() { } public Goods(String name, double price) { this.name = name; this.price = price; }
public String getName() { return name; }
public double getPrice() { return price; }
@Override public String toString() { return "Goods{" + "name='" + name + '\'' + ", price=" + price + '}'; } } public class Comparator1 { public static void main(String[] args) { Goods[] goods = new Goods[5]; goods[0] = new Goods("xiaomi",15); goods[1] = new Goods("huawei",12.6); goods[2] = new Goods("dell",23); goods[3] = new Goods("asus",29); goods[4] = new Goods("iphone",49); Arrays.sort(goods, new Comparator() { @Override public int compare(Object o1, Object o2) { if(o1 instanceof Goods && o2 instanceof Goods){ Goods s1 = (Goods) o1; Goods s2 = (Goods) o2; return -Double.compare(s1.getPrice(),s2.getPrice()); } throw new RuntimeException(); } }); System.out.println(Arrays.toString(goods)); } }
|
System 类的常用方法
System.getProperty(string)
方法接受不同的参数获取不同的值
java.version
获取Java运行时环境版本
java.home
获取Java安装目录
os.name
操作系统的名称
os.version
操作系统版本
user.name
用户账户名称
user.home
用户主目录
user.dir
用户的当前工作目录
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| System.out.println(System.getProperty("java.version"));
System.out.println(System.getProperty("java.home"));
System.out.println(System.getProperty("os.name"));
System.out.println(System.getProperty("os.version"));
System.out.println(System.getProperty("user.name"));
System.out.println(System.getProperty("user.home"));
System.out.println(System.getProperty("user.dir"));
|
Math 类的常用方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| System.out.println(Math.abs(-34));
System.out.println(Math.sqrt(120.2));
System.out.println(Math.pow(10, 3));
System.out.println(Math.log(12));
System.out.println(Math.max(12, 33));
System.out.println(Math.min(12, 33));
System.out.println(Math.random());
|