一、字符串相关的类
|-String
String字符串,使用一对“”引起来表示
①String声明为final的,不可被继承
②String实现了Serializable接口:表示字符串是支持序列化的
实现了Comparable接口:表示String可以比较大小
③String内部定义了final char[] value用于存储字符串数据
④String代表不可变的字符序列,简称:不可变性
体现:
|-当对字符串重新赋值时,需要重写指定内存区域赋值,不能使用原有的value进行赋值
|-当对现有的字符串进行来连接操作时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值
|-当调用String的replace()方法修改指定字符或字符串时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值
⑤通过字面量的方式(区别于new)给一个字符串赋值,此时的字符串值声明在字符串常量池中
⑥字符串常量池中是不会存储相同内容的字符串的
例:
package com.atguigu.java;
import org.junit.Test;
//String的使用
public class StringTest {
@Test
public void test1() {
String s1 = "abc";//字面量的定义方式
String s2 = "abc";
//s1 = "hello";
System.out.println(s1 == s2);//比较地址值
System.out.println(s1);
System.out.println(s2);
System.out.println("------------------------------");
String s3 = "abc";
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);
System.out.println(s5);
}
}
|-String不同实例化方式的对比
例:
package com.atguigu.java;
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
}
package com.atguigu.java;
import org.junit.Test;
//String的使用
public class StringTest {
//String的实例化方式:
//方式一:通过字面量定义的方式
//方式二:通过new + 构造器的方式
@Test
public void test2() {
//通过字面量定义的方式:此时的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);
System.out.println(s1 == s3);
System.out.println(s1 == s4);
System.out.println(s3 == s4);
System.out.println("------------------------");
Person p1 = new Person("Tom", 12);
Person p2 = new Person("Tom", 12);
System.out.println(p1.name.equals(p2.name));
System.out.println(p1.name == p2.name);
p1.name = "Jerry";
System.out.println(p2.name);
}
}
面试题:String s = new String (“abc”);方式创建对象,在内存中创建了几个对象?
两个:一个是堆空间中new结构,另一个是char[]对应的常量池中的数据:“abc”
|-String不同拼接操作的对比、
例:
package com.atguigu.java;
import org.junit.Test;
//String的使用
public class StringTest {
@Test
public void test3() {
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);
System.out.println(s3 == s5);
System.out.println(s3 == s6);
System.out.println(s3 == s7);
System.out.println(s5 == s6);
System.out.println(s5 == s7);
System.out.println(s6 == s7);
String s8 = s5.intern();//返回值得到的s8使用的常量值中已经存在的“javaEEhadoop”
System.out.println(s3 == s8);
}
}
结论:
①常量与常量的拼接结果在常量池。且常量池中不会存在相同内容的常量。
②只要其中有一个是变量,结果就在堆中
③如果拼接的结果调用intern()方法,返回值就在常量池中
|-String面试题:
package com.atguigu.exer;
public class StringTest {
String str = new String("good");
char[] ch = {'t', 'e', 's', 't'};
public void change(String str, char ch[]) {
str = "test ok";
ch[0] = 'b';
}
public static void main(String[] args) {
StringTest ex = new StringTest();
ex.change(ex.str, ex.ch);
// System.out.print(ex.str + " and ");
System.out.println(ex.str);//
System.out.println(ex.ch);//
}
}
|-String的常用方法:
intlength():返回字符串的长度:returnvalue.length
charcharAt(intindex):返回某索引处的字符returnvalue[index]
booleanisEmpty():判断是否是空字符串:returnvalue.length==0
StringtoLowerCase():使用默认语言环境,将String中的所有字符转换为小写
StringtoUpperCase():使用默认语言环境,将String中的所有字符转换为大写
Stringtrim():返回字符串的副本,忽略前导空白和尾部空白
booleanequals(Objectobj):比较字符串的内容是否相同
booleanequalsIgnoreCase(StringanotherString):与equals方法类似,忽略大小写
Stringconcat(Stringstr):将指定字符串连接到此字符串的结尾。等价于用“+”
intcompareTo(StringanotherString):比较两个字符串的大小
Stringsubstring(intbeginIndex):返回一个新的字符串,它是此字符串的从beginIndex开始截取到最后的一个子字符串。
Stringsubstring(intbeginIndex,intendIndex):返回一个新字符串,它是此字符串从beginIndex开始截取到endIndex(不包含)的一个子字符串
例:
package com.atguigu.java;
import org.junit.Test;
public class StringMethodTest {
@Test
public void test2() {
String s1 = "Helloworld";
String s2 = "helloworld";
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));
String s3 = "abc";
String s4 = s3.concat("def");
System.out.println(s4);
String s5 = "abc";
String s6 = new String("abe");
System.out.println(s5.compareTo(s6));//涉及到字符串排序
String s7 = "天宇鸿图软件工程有限公司";
String s8 = s7.substring(2);
System.out.println(s7);
System.out.println(s8);
String s9 = s7.substring(4, 12);
System.out.println(s9);
}
@Test
public void test1() {
String s1 = "Helloworld";
System.out.println(s1.length());
System.out.println(s1.charAt(0));
System.out.println(s1.charAt(9));
System.out.println(s1.charAt(5));
System.out.println(s1.isEmpty());
String s2 = s1.toLowerCase();
System.out.println(s1);//s1是不可变的,仍为原来的字符串
System.out.println(s2);//改成小写以后的字符串
String s3 = " he ll o wor l d ";
String s4 = s3.trim();
System.out.println("-----" + s3 + "-----");
System.out.println("-----" + s4 + "-----");
}
}
|-String的常用方法2:
booleanendsWith(Stringsuffix):测试此字符串是否以指定的后缀结束
booleanstartsWith(Stringprefix):测试此字符串是否以指定的前缀开始
booleanstartsWith(Stringprefix,inttoffset):测试此字符串从指定索引开始的子字符串是否以指定前缀开始
boolean contains(CharSequence s):当且仅当此字符串包含指定的char 值序列时,返回true
lint indexOf(String str):返回指定子字符串在此字符串中第一次出现处的索引
lint indexOf(String str, int fromIndex):返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始
lint lastIndexOf(String str):返回指定子字符串在此字符串中最右边出现处的索引
lint lastIndexOf(String str, int fromIndex):返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索
注:indexOf和lastIndexOf方法如果未找到都是返回-1
例:
package com.atguigu.java;
import org.junit.Test;
public class StringMethodTest {
@Test
public void test3() {
String str1 = "helloworld";
boolean b1 = str1.endsWith("ld");
System.out.println(b1);
boolean b2 = str1.startsWith("He");
System.out.println(b2);
boolean b3 = str1.startsWith("ll", 2);
System.out.println(b3);
String str2 = "wor";
System.out.println(str1.contains(str2));
System.out.println(str1.indexOf("lol"));
System.out.println(str1.indexOf("lo", 5));
String str3 = "hellorworld";
System.out.println(str3.lastIndexOf("or"));
System.out.println(str3.lastIndexOf("or", 6));
}
}
什么情况下,indexof(str)和lastIndexof(str)返回值相同:
情况一:存在唯一的str
情况二:不存在
|-String的常用方法3:
Stringreplace(charoldChar,charnewChar):返回一个新的字符串,它是通过用newChar替换此字符串中出现的所有oldChar得到的。
Stringreplace(CharSequencetarget,CharSequencereplacement):使用指定的字面值替换序列替换此字符串所有匹配字面值目标序列的子字符串。
StringreplaceAll(Stringregex,Stringreplacement):使用给定的replacement替换此字符串所有匹配给定的正则表达式的子字符串StringreplaceFirst(Stringregex,Stringreplacement):使用给定的replacement替换此字符串匹配给定的正则表达式的第一个子字符串。
booleanmatches(Stringregex):告知此字符串是否匹配给定的正则表达式。
String[]split(Stringregex):根据给定正则表达式的匹配拆分此字符串。
String[]split(Stringregex,intlimit):根据匹配给定的正则表达式来拆分此字符串,最多不超过limit个,如果超过了,剩下的全部都放到最后一个元素中。
例:
package com.atguigu.java;
import org.junit.Test;
public class StringMethodTest {
@Test
public void test4() {
String str1 = "天宇鸿图软件工程有限公司";
String str2 = str1.replace("软件工程", "信息技术");
System.out.println(str1);
System.out.println(str2);
System.out.println("-----------------------------------");
String str = "12hello34world5java7891mysql456";
//把字符串中的数字替换成,,如果结果中开头和结尾有,的话去掉
String string = str.replaceAll("\\d+", ",").replaceAll("^,|,$", "");
System.out.println(string);
System.out.println("--------------------------------");
str = "12345";
//判断str字符串中是否全部有数字组成,即有1-n个数字组成
boolean matches = str.matches("\\d+");
System.out.println(matches);
String tel = "0571-4534289";
//判断这是否是一个杭州的固定电话
boolean result = tel.matches("0571-\\d{7,8}");
System.out.println(result);
System.out.println("--------------------------------");
str = "hello|world|java";
String[] strs = str.split("\\|");
for (int i = 0; i < strs.length; i++) {
System.out.println(strs[i]);
}
System.out.println();
str2 = "hello.world.java";
String[] strs2 = str2.split("\\.");
for (int i = 0; i < strs2.length; i++) {
System.out.println(strs2[i]);
}
}
}
|-String与基本数据类型包装类的转换
package com.atguigu.java;
import org.junit.Test;
public class StringTest1 {
//String与基本数据类型、包装类的转换:调用包装类的静态方法:parseXxx(str)
@Test
public void test1() {
String str1 = "123";
int num = Integer.parseInt(str1);
//基本数据类型、包装类转换为String:调用String重载的Valueof(xxx)
String str2 = String.valueOf(num);
String str3 = num + "";
System.out.println(str1 == str3);
}
}
|-String与char[]之间的转换
package com.atguigu.java;
import org.junit.Test;
public class StringTest1 {
//String与char[]转换:调用String的toCharArray()
@Test
public void test2() {
String str1 = "abc123";
char[] charArray = str1.toCharArray();
for (int i = 0; i < charArray.length; i++) {
System.out.println(charArray[i]);
}
//char[]与String转换:调用String的构造器
char[] arr = new char[]{'h','e','l','l','o'};
String str2 = new String(arr);
System.out.println(str2);
}
}
|-String与byte[]之间的转换
package com.atguigu.java;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class StringTest1 {
//String与byte[]转换:调用String的getBytes()
@Test
public void test3() throws UnsupportedEncodingException {
String str1 = "abc123中国";
byte[] bytes = str1.getBytes();//使用默认的字符集进行转换
System.out.println(Arrays.toString(bytes));
byte[] gbks = str1.getBytes("gbk");//使用gbk字符集进行编码
System.out.println(Arrays.toString(gbks));
//byte[]转换为String:调用String的构造器
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);//没有出现乱码,原因:编码集和解码集一致
//说明:解码时,要求解码使用的字符集必需与编码时使用的字符集一致,否则会出现乱码
}
}
|-解决拼接问题
package com.atguigu.java;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class StringTest1 {
@Test
public void test4() {
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
}
}
|-StringBuffer、StringBuilder
①String、StringBuffer、StringBuilder三者的异同:
String:不可变的字符序列,底层使用char[]存储
StringBuffer:可变的字符序列,线程安全、效率低,底层使用char[]存储
StringBuilder:可变的字符序列,线程不安全、效率高,底层使用char[]存储
②源码分析:
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的数组
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,同时将原有数组中的元素赋值到新的数组中
例:
package com.atguigu.java;
import org.junit.Test;
public class StringBufferBuilderTest {
@Test
public void test1() {
StringBuffer sb1 = new StringBuffer("abc");
sb1.setCharAt(0, 'm');
System.out.println(sb1);
StringBuffer sb2 = new StringBuffer();
System.out.println(sb2.length());
}
}
|-StringBuffer类的常用方法:
StringBuffer append(xxx):提供了很多的append()方法,用于进行字符串拼接StringBuffer delete(int start,int end):删除指定位置的内容
StringBuffer replace(int start, int end, String str):把[start,end)位置替换为str StringBuffer insert(int offset, xxx):在指定位置插入xxx
StringBuffer reverse() :把当前字符序列逆转
public int indexOf(String str)
public String substring(int start,int end):返回一个从start开始到end索引结束的左闭右开区间的子字符串
public int length()
public char charAt(int n )
public void setCharAt(int n ,char ch)
例:
package com.atguigu.java;
import org.junit.Test;
public class StringBufferBuilderTest {
@Test
public void test2() {
StringBuffer s1 = new StringBuffer("abc");
s1.append(1);
s1.append("1");
System.out.println(s1);
// s1.delete(2, 4);
// s1.replace(2, 4, "hello");
// s1.insert(2, false);
// s1.reverse();
String s2 = s1.substring(1, 3);
System.out.println(s1);
System.out.println(s1.length());
System.out.println(s2);
}
}
|-String、StringBuffer、StringBuilder效率对比
从高到低排列:
StringBuilder > StringBuffer > String
例:
package com.atguigu.java;
import org.junit.Test;
public class StringBufferBuilderTest {
@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));
}
}
二、JDK8之前日期时间API
①java.lang.System类:
System类提供的public static long currentTimeMillis()用来返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差。此方法适于计算时间差。
例:
package com.atguigu.java;
import org.junit.Test;
public class DateTimeTest {
@Test
public void test1() {
//返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差
//称为时间戳
long time = System.currentTimeMillis();
System.out.println(time);
}
}
②java.util.Date类
表示特定的瞬间,精确到毫秒
构造器:
Date():使用无参构造器创建的对象可以获取本地当前时间。
Date(long date)
常用方法
getTime():返回自1970 年1 月1 日00:00:00 GMT 以来此Date 对象表示的毫秒数。
toString():把此Date 对象转换为以下形式的String:dowmonddhh:mm:sszzzyyyy其中:dow是一周中的某一天(Sun, Mon, Tue, Wed, Thu, Fri, Sat),zzz是时间标准。
其它很多方法都过时了。
例:
import org.junit.Test;
import java.util.Date;
public class DateTimeTest {
@Test
public void test2() {
//构造器一:Date():创建一个对应当前时间Date对象
Date date1 = new Date();
System.out.println(date1.toString());//Sun Dec 20 16:19:27 CST 2020
System.out.println(date1.getTime());//1608452460653
//构造器二:创建指定毫秒数的Date对象
Date date2 = new Date(1608452460653l);
System.out.println(date2.toString());
//将java.util.Date对象转换为java.sql.Date对象
//情况一:
// Date date4 = new java.sql.Date(1608452460653l);
// java.sql.Date date5 = (java.sql.Date) date4;
//情况二:
Date date6 = new Date();
java.sql.Date date7 = new java.sql.Date(date6.getTime());
}
}
|-String算法题
1.模拟一个trim方法,去除字符串两端的空格。
2.将一个字符串进行反转。将字符串中指定部分进行反转。比如将“abcdefg”反转为”abfedcg”
3.获取一个字符串在另一个字符串中出现的次数。
比如:获取“ab”在 “cdabkkcadkabkebfkabkskab”
中出现的次数
4.获取两个字符串中最大相同子串。比如:
str1 = "abcwerthelloyuiodef“;str2 = "cvhellobnm"//10
提示:将短的那个串进行长度依次递减的子串与较长
的串比较。
5.对字符串中字符进行自然顺序排序。"abcwerthelloyuiodef"
提示:
1)字符串变成字符数组。
2)对数组排序,选择,冒泡,Arrays.sort(str.toCharArray());
3)将排序后的数组变成字符串
例:
package caom.atguigu.exer;
import org.junit.Test;
import java.util.Arrays;
public class StringExer {
// 第1题
public String myTrim(String str) {
if (str != null) {
int start = 0;// 用于记录从前往后首次索引位置不是空格的位置的索引
int end = str.length() - 1;// 用于记录从后往前首次索引位置不是空格的位置的索引
while (start < end && str.charAt(start) == ' ') {
start++;
}
while (start < end && str.charAt(end) == ' ') {
end--;
}
if (str.charAt(start) == ' ') {
return "";
}
return str.substring(start, end + 1);
}
return null;
}
// 第2题
// 方式一:
public String reverse1(String str, int start, int end) {// start:2,end:5
if (str != null) {
// 1.
char[] charArray = str.toCharArray();
// 2.
for (int i = start, j = end; i < j; i++, j--) {
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
}
// 3.
return new String(charArray);
}
return null;
}
// 方式二:
public String reverse2(String str, int start, int end) {
// 1.
String newStr = str.substring(0, start);// ab
// 2.
for (int i = end; i >= start; i--) {
newStr += str.charAt(i);
} // abfedc
// 3.
newStr += str.substring(end + 1);
return newStr;
}
// 方式三:推荐 (相较于方式二做的改进)
public String reverse3(String str, int start, int end) {// ArrayList list = new ArrayList(80);
// 1.
StringBuffer s = new StringBuffer(str.length());
// 2.
s.append(str.substring(0, start));// ab
// 3.
for (int i = end; i >= start; i--) {
s.append(str.charAt(i));
}
// 4.
s.append(str.substring(end + 1));
// 5.
return s.toString();
}
@Test
public void testReverse() {
String str = "abcdefg";
String str1 = reverse3(str, 2, 5);
System.out.println(str1);// abfedcg
}
// 第3题
// 判断str2在str1中出现的次数
public int getCount(String mainStr, String subStr) {
if (mainStr.length() >= subStr.length()) {
int count = 0;
int index = 0;
// while((index = mainStr.indexOf(subStr)) != -1){
// count++;
// mainStr = mainStr.substring(index + subStr.length());
// }
// 改进:
while ((index = mainStr.indexOf(subStr, index)) != -1) {
index += subStr.length();
count++;
}
return count;
} else {
return 0;
}
}
@Test
public void testGetCount() {
String str1 = "cdabkkcadkabkebfkabkskab";
String str2 = "ab";
int count = getCount(str1, str2);
System.out.println(count);
}
@Test
public void testMyTrim() {
String str = " a ";
// str = " ";
String newStr = myTrim(str);
System.out.println("---" + newStr + "---");
}
// 第4题
// 如果只存在一个最大长度的相同子串
public String getMaxSameSubString(String str1, String str2) {
if (str1 != null && str2 != null) {
String maxStr = (str1.length() > str2.length()) ? str1 : str2;
String minStr = (str1.length() > str2.length()) ? str2 : str1;
int len = minStr.length();
for (int i = 0; i < len; i++) {// 0 1 2 3 4 此层循环决定要去几个字符
for (int x = 0, y = len - i; y <= len; x++, y++) {
if (maxStr.contains(minStr.substring(x, y))) {
return minStr.substring(x, y);
}
}
}
}
return null;
}
// 如果存在多个长度相同的最大相同子串
// 此时先返回String[],后面可以用集合中的ArrayList替换,较方便
public String[] getMaxSameSubString1(String str1, String str2) {
if (str1 != null && str2 != null) {
StringBuffer sBuffer = new StringBuffer();
String maxString = (str1.length() > str2.length()) ? str1 : str2;
String minString = (str1.length() > str2.length()) ? str2 : str1;
int len = minString.length();
for (int i = 0; i < len; i++) {
for (int x = 0, y = len - i; y <= len; x++, y++) {
String subString = minString.substring(x, y);
if (maxString.contains(subString)) {
sBuffer.append(subString + ",");
}
}
System.out.println(sBuffer);
if (sBuffer.length() != 0) {
break;
}
}
String[] split = sBuffer.toString().replaceAll(",$", "").split("\\,");
return split;
}
return null;
}
// 如果存在多个长度相同的最大相同子串:使用ArrayList
// public List<String> getMaxSameSubString1(String str1, String str2) {
// if (str1 != null && str2 != null) {
// List<String> list = new ArrayList<String>();
// String maxString = (str1.length() > str2.length()) ? str1 : str2;
// String minString = (str1.length() > str2.length()) ? str2 : str1;
//
// int len = minString.length();
// for (int i = 0; i < len; i++) {
// for (int x = 0, y = len - i; y <= len; x++, y++) {
// String subString = minString.substring(x, y);
// if (maxString.contains(subString)) {
// list.add(subString);
// }
// }
// if (list.size() != 0) {
// break;
// }
// }
// return list;
// }
//
// return null;
// }
@Test
public void testGetMaxSameSubString() {
String str1 = "abcwerthelloyuiodef";
String str2 = "cvhellobnmiodef";
String[] strs = getMaxSameSubString1(str1, str2);
System.out.println(Arrays.toString(strs));
}
// 第5题
@Test
public void testSort() {
String str = "abcwerthelloyuiodef";
char[] arr = str.toCharArray();
Arrays.sort(arr);
String newStr = new String(arr);
System.out.println(newStr);
}
}
|-IDEADeBug调试
例:
package com.atguigu.java;
import org.junit.Test;
public class IDEADebug {
@Test
public void testStringBuffer() {
String str = null;
StringBuffer sb = new StringBuffer();
sb.append(str);
System.out.println(sb.length());
System.out.println(sb);
StringBuffer sb1 = new StringBuffer(str);//NullPointerException
System.out.println(sb1);
}
}
|-SimpleDateFormat的使用
格式化:
SimpleDateFormat() :默认的模式和语言环境创建对象
public SimpleDateFormat(String pattern):该构造方法可以用参数pattern指定的格式创建一个对象,该对象调用:
public String format(Date date):方法格式化时间对象date
解析:
public Date parse(String source):从给定字符串的开始解析文本,以生成一个日期。
例:
package com.atguigu.java;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
//jdk8之前日期时间API测试
public class DateTimeTest {
@Test
public void testSimpleDateFormat() throws ParseException {
//实例化SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat();
//格式化:日期-->字符串
Date date = new Date();
System.out.println(date);
String format = sdf.format(date);
System.out.println(format);
//解析:格式化的逆过程,字符串-->日期
String str = "20-12-20 下午6:07";
Date date1 = sdf.parse(str);
System.out.println(date1);
System.out.println("按照指定的方式格式化:调用带参构造器");
//SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy-MM-dd hh:mm:ss");
String format1 = sdf1.format(date);
System.out.println(format1);
//解析:要求字符串必须符合 SimpleDateFormat识别的格式(通过构造器参数体现),否则就报异常
Date date2 = sdf1.parse("2020-12-20 06:16:02");
System.out.println(date2);
}
}
|-练习
例:
package com.atguigu.java;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
//jdk8之前日期时间API测试
public class DateTimeTest {
@Test
public void testwxer() throws ParseException {
String birth = "2020-09-08";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy-MM-dd");
Date date = sdf1.parse(birth);
java.sql.Date birthDate = new java.sql.Date(date.getTime());
System.out.println(birthDate);
}
}
|-calendar日历类(抽象类)的使用
package com.atguigu.java;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
//jdk8之前日期时间API测试
public class DateTimeTest {
//Calendar日历类的使用
@Test
public void testCalendar() {
//1.实例化
//方式一:创建其子类(GregorianCalendar)的对象
//方式二:调用其静态方法getInstance()
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.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);
}
}
三、JDK8中新日期时间API
|-LocalDate 、 LocalTime 、 LocalDateTime的使用
说明:
①LocalDateTime相较于LocalDate、LocalTime,使用频率高
②类似于Calendr
例:
package com.atguigu.java;
import org.junit.Test;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
//JDK 8中日期时间API的测试
public class JDK8DateTimeTest {
//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, 6, 13, 23, 43);
System.out.println(localDateTime1);
//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());
//体现不可变性
//withXxx():设置相关的属性
LocalDate localDate1 = localDate.withDayOfMonth(22);
System.out.println(localDate);
System.out.println(localDate1);
LocalDateTime localDateTime2 = localDateTime.withHour(4);
System.out.println(localDateTime);
System.out.println(localDateTime2);
//不可变性
LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
System.out.println(localDateTime);
System.out.println(localDateTime3);
LocalDateTime localDateTime4 = localDateTime.minusDays(6);
System.out.println(localDateTime);
System.out.println(localDateTime4);
}
}
|-Instant类的使用
Instant:时间线上的一个瞬时点。 这可能被用来记录应用程序中的事件时间戳,类似于java.util.Date类
例:
package com.atguigu.java;
import org.junit.Test;
import java.time.*;
import java.util.Date;
//JDK 8中日期时间API的测试
public class JDK8DateTimeTest {
//Instant的使用
@Test
public void test2() {
//now():获取本初子午线对应的标准时间
Instant instant = Instant.now();
System.out.println(instant);//2020-12-21T09:24:41.197Z
//添加时间的偏移量
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime);
//toEpochMilli():获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数
long milli = instant.toEpochMilli();
System.out.println(milli);
//ofEpochMilli():通过给定的毫秒数,获取Instant实例,类似于:Date类的getTime()
Instant instant1 = Instant.ofEpochMilli(1608543132686L);
System.out.println(instant1);
}
}
|-DateTimeFormatter的使用
格式化或解析日期、时间,类似于SimleDateFormat
例:
package com.atguigu.java;
import org.junit.Test;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalAccessor;
import java.util.Date;
//JDK 8中日期时间API的测试
public class JDK8DateTimeTest {
//DateTimeFormatter格式化或解析日期、时间,类似于SimleDateFormat
@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);
System.out.println(str1);
//解析:字符串-->日期
TemporalAccessor parse = formatter.parse("2020-12-22T11:12:18.151");
System.out.println(parse);
//方式二:本地化相关的格式ofLocalizedDateTime(FormatStyle.LONG)
DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
//格式化:
String str2 = formatter1.format(localDateTime);
System.out.println(str2);
//本地化相关的格式。如:ofLocalizedDateTime(FormatStyle.LONG)
DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
//格式化
String str3 = formatter2.format(LocalDate.now());
System.out.println(str3);
//方式三: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);
//解析
TemporalAccessor accessor = formatter3.parse("2020 12 22 11:27:37");
System.out.println(accessor);
}
}
四、Java比较器
自然排序:java.lang.Comparable
定制排序:java.util.Comparator|-Comparbale接口的使用:自然排序
①重写compareTo()方法的规则:
如果当前对象this大于形参对象obj,则返回正整数
如果当前对象this小于形参对象obj,则返回负整数
如果当前对象this等于形参对象obj,则返回零
例:
package com.atguigu.java;
import org.junit.Test;
import java.util.Arrays;
//Comparable接口的使用
public class CompareTest {
//String、包装类等实现了Comparable接口,重写了compareTo()方法,给出了比较两个对象大小的方式
//String、包装类重写了compareTo()方法以后,进行了从小到大的排列
@Test
public void test1() {
String[] arr = new String[]{"AA", "CC", "KK", "MM", "JJ", "DD"};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
②:
对于自定义类,如果需要排序,可以让自定义类实现Compareable接口,重写compareTo()方法,在compareTo(obj)方法中指明如何排序
package com.atguigu.java;
//商品类
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);
}
//方式二:
// Double.compare(this.price,Goods.price);
}
throw new RuntimeException("传入的数据类型不一致!");
}
}
package com.atguigu.java;
import org.junit.Test;
import java.util.Arrays;
//Comparable接口的使用
public class CompareTest {
@Test
public void test2() {
Goods[] arr = new Goods[5];
arr[0] = new Goods("联想鼠标", 24);
arr[1] = new Goods("戴尔鼠标", 43);
arr[2] = new Goods("小米鼠标", 12);
arr[3] = new Goods("华为鼠标", 65);
arr[4] = new Goods("microsoft鼠标", 43);
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
|-Comparator实现定制排序
适用场景:
当元素的类型没有实现java.lang.Comparable接口而又不方便修改代码,或者实现了java.lang.Comparable接口的排序规则不适合当前的操作,那么可以考虑使用 Comparator 的对象来排序
重写规则:
重写compare(Object o1,Object o2)方法,比较o1和o2的大小:
如果方法返回正整数,则表示o1大于o2;
如果返回0,表示相等;
返回负整数,表示o1小于o2
例一:
package com.atguigu.java;
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
//Comparable接口的使用
public class CompareTest {
//Comparator:定制排序
@Test
public void test3() {
String[] arr = new String[]{"AA", "CC", "KK", "MM", "JJ", "DD"};
Arrays.sort(arr, new Comparator<String>() {
//按照字符串从大到小的顺序排列
@Override
public int compare(String o1, String 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));
}
}
}
例二:
package com.atguigu.java;
//商品类
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);
}
//方式二:
// Double.compare(this.price,Goods.price);
}
throw new RuntimeException("传入的数据类型不一致!");
}
}
package com.atguigu.java;
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
//Comparable接口的使用
public class CompareTest {
@Test
public void teste4() {
Goods[] arr = new Goods[6];
arr[0] = new Goods("联想鼠标", 24);
arr[1] = new Goods("戴尔鼠标", 43);
arr[2] = new Goods("小米鼠标", 12);
arr[3] = new Goods("华为鼠标", 65);
arr[4] = new Goods("华为鼠标", 224);
arr[5] = new Goods("microsoft鼠标", 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));
}
}
|-Comparable接口与Comparator接口使用的对比:
Comparable接口的方式一旦指定,保证Comparable接口实现类的对象在任何位置都可以比较大小
Comparator接口属于临时性的比较,
五、System类
成员变量
System类内部包含in、out和err三个成员变量,分别代表标准输入流(键盘输入),标准输出流(显示器)和标准错误输出流(显示器)。
成员方法:
native long currentTimeMillis():
该方法的作用是返回当前的计算机时间,时间的表达格式为当前计算机时间和GMT时间(格林威治时间)1970年1月1号0时0分0秒所差的毫秒数。
void exit(int status):
该方法的作用是退出程序。其中status的值为0代表正常退出,非零代表异常退出。使用该方法可以在图形界面编程中实现程序的退出功能等。
例:
package com.atguigu.java;
import org.junit.Test;
public class OthereClassTest {
@Test
public void test1() {
String javaVersion = System.getProperty("java.version");
System.out.println("java的version:" + javaVersion);
String javaHome = System.getProperty("java.home");
System.out.println("java的home:" + javaHome);
String osName = System.getProperty("os.name");
System.out.println("os的name:" + osName);
String osVersion = System.getProperty("os.version");
System.out.println("os的version:" + osVersion);
String userName = System.getProperty("user.name");
System.out.println("user的name:" + userName);
String userHome = System.getProperty("user.home");
System.out.println("user的home:" + userHome);
String userDir = System.getProperty("user.dir");
System.out.println("user的dir:" + userDir);
}
}
六、Math类
ava.lang.Math提供了一系列静态方法用于科学计算。其方法的参数和返回值类型一般为double型。
abs 绝对值
acos,asin,atan,cos,sin,tan 三角函数
sqrt 平方根
pow(double a,doble b) a的b次幂
log 自然对数
exp e为底指数
max(double a,double b)
min(double a,double b)
random() 返回0.0到1.0的随机数
long round(double a) double型数据a转换为long型(四舍五入)
toDegrees(double angrad) 弧度—>角度
toRadians(double angdeg) 角度—>弧度
七、BigInteger类与BigDecimal类
|-BigInteger类
构造器:
BigInteger(String val):根据字符串构建BigInteger对象
常用方法:
public BigInteger abs():返回此BigInteger 的绝对值的BigInteger。
BigInteger add(BigInteger val) :返回其值为(this + val) 的BigInteger
BigInteger subtract(BigInteger val) :返回其值为(this -val) 的BigInteger
BigInteger multiply(BigInteger val) :返回其值为(this * val) 的BigInteger
BigInteger divide(BigInteger val) :返回其值为(this / val) 的BigInteger。整数相除只保留整数部分。
BigInteger remainder(BigInteger val) :返回其值为(this % val) 的BigInteger。
BigInteger[] divideAndRemainder(BigInteger val):返回包含(this / val) 后跟(this % val) 的两个BigInteger 的数组。
BigInteger pow(int exponent) :返回其值为(thisexponent) 的BigInteger。
|-BigDecimal类
构造器:
public BigDecimal(double val)
public BigDecimal(String val)
常用方法:
public BigDecimal add(BigDecimal augend)
public BigDecimal subtract(BigDecimal subtrahend)
public BigDecimal multiply(BigDecimal multiplicand)
public BigDecimal divide(BigDecimal divisor, intscale, introundingMode)
例:
package com.atguigu.java;
import org.junit.Test;
import java.math.BigDecimal;
import java.math.BigInteger;
public class OthereClassTest {
@Test
public void test2() {
BigInteger bi = new BigInteger("12433241123");
BigDecimal bd = new BigDecimal("12435.351");
BigDecimal bd2 = new BigDecimal("11");
System.out.println(bi);
// System.out.println(bd.divide(bd2));
System.out.println(bd.divide(bd2, BigDecimal.ROUND_HALF_UP));
System.out.println(bd.divide(bd2, 15, BigDecimal.ROUND_HALF_UP));
}
}