目录

  • 一、 字符串相关的类
    • 1、创建字符串
    • 2、String常用方法
    • 3、StringBuffer
      • StringBuffer类的常用方法
    • 4、StringBuilder
  • 二、JDK 8之前的日期时间API
    • 1、System
    • 2、Date类
    • 3、SimpleDateFormat
    • 4、Calendar
  • 三、JDK8中新日期时间API
    • 1、新日期时间API出现的背景
    • 2、LocalDate、LocalTime、LocalDateTime
    • 3、 瞬时:Instant
    • 4、格式化与解析日期或时间 DateTimeFormatter
    • 5、其它API
    • 6、参考:与传统日期处理的转换
  • 四、Java比较器
    • 1、方式一:自然排序:java.lang.Comparable(comparable接口)
    • 2、方式二:定制排序:java.util.Comparator(Comparator接口)
  • 五、System类
  • 六、Math类
  • 七、BigInteger与BigDecimal
    • 1、BigInteger类
    • 2、BigDecimal类

一、 字符串相关的类

1、创建字符串

String的特性

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


具体JDK API String 方法属性解析:https://www.runoob.com/manual/jdk11api/java.base/java/lang/String.html

  1. String对象的字符内容是存储在一个字符数组中的。 底层原理就是String字符串就是一个数组。
  2. private意味着外面无法直接获取字符数组,而且Strinq没有提供value的qet和set方法,

创建字符串最简单的方式如下:

String s1 = "abc";

在代码中遇到字符串常量时,这里的值是 “abc”",编译器会使用该值创建一个 String 对象。

和其它对象一样,可以使用关键字和构造方法来创建 String 对象。

用构造函数创建字符串:

String str1=new String(“abc”);
String 创建的字符串存储在公共池中,而 new 创建的字符串对象在堆上:


String str1 = “abc”;与String str2 = new String(“abc”);的区别?

面试题:string s = new String(“abc”);方式创建对象,在内存中创建了几个对象?
两个:一个是堆空间中new结构,另一个是char[]对应的常量池中的数据: “abc”


import org.junit.Test;/*** @Description: $ String 的使用* @Author: dyq* @Date: $*/
public class StringTest {/**结论:
1.常量与常量的拼接结果在常量池。且常量池中不会存在相同内容的常量。
* 2.只要其中有一个是变量,结果就在堆中
* 3.如果拼接的结果调用intern()方法,返回值就在常量池中* */@Testpublic  void test3() {String s1 = "Java";String s2 ="hello";String s3 = "Javahello";String s4= "Java"+"hello";String s5 =s1+"hello";String s6="Java"+s2;System.out.println(s3==s4);//trueSystem.out.println(s3==s5);//falseSystem.out.println(s3==s6);//falseSystem.out.println(s5==s6);//falseSystem.out.println(s4==s6);//falseString s7 = s6.intern(); //返回值得到的s8使用的常量值中已经存在的"Javahello" intern() 返回字符串对象的规范表示。System.out.println(s7==s3);//true}/*String 的实例化方式方式一:通过字面量定义的方式方式二:通过new+构造器的方式* */@Testpublic  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); //trueSystem.out.println(s3==s4);  //false}/*String字符串,使用一对""引起来表示1,String声明为final的,不可被继承2,String实现Serializable接口:表示字符串是支持序列化的。实现Comparable接口:表示String可以比较大小。3.String内部定义了final char[] value 用于存储字符串数据4.String:代表不可变的字符序列,简称:不可变性体现:1,当对字符串重新赋值时,需要重写指定内存区域赋值,不能使用原有的value进行赋值2,当对现有的字符串进行连接操作时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值3.当调用string的replace()方法修改指定字符或字符串时,也需要重新指定内存区域赋值,原有的value进行赋值5.通过字面量的方式(区别于new)给一个字符串赋值,此时的字符串值声明在字符串常量池中。6.字符串常量池中是不会存储相同内容的字符串的。* */@Testpublic  void test1(){String s1 = "abc";  //字面量的定义方式String s2 = "abc";s1 = "hello";System.out.println(s1);//helloSystem.out.println(s2);//abcSystem.out.println(s1.equals(s2));  //比较s1和s2的地址值 flaseSystem.out.println("*********************");s1 += "diaolove";System.out.println(s1); //hellodiaoloveSystem.out.println("*********************");String s4 = "abc";String s5 = s4.replace('a', 'b');  // replace是返回从替换所有出现的导致一个字符串 oldChar在此字符串 newChar 。System.out.println(s5);  //bbcint len = s1.length();System.out.println("字符串的长度为" + len);int hash = s1.hashCode();System.out.println(hash);}}

一道面试题:

public class StringTest1 {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) {StringTest1 ex = new StringTest1();ex.change(ex.str, ex.ch);System.out.print(ex.str + " and ");//goodSystem.out.println(ex.ch); //best}
}

2、String常用方法

方法 解析
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): 测试此字符串从指定索引开始的子字符串是否以指定前缀开始
boolean contains(CharSequence s): 当且仅当此字符串包含指定的 char 值序列时,返回 true
int indexOf(String str): 返回指定子字符串在此字符串中第一次出现处的索引
int indexOf(String str, int fromIndex): 返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始
int lastIndexOf(String str): 返回指定子字符串在此字符串中最右边出现处的索引
int lastIndexOf(String str, int fromIndex): 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索注意: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个,如果超过了,剩下的全部都放到最后一个元素中。
public class StringTest3 {public static void main(String[] args) {String str = "12hello34world5java7891mysql456";//把字符串中的数字替换成,,如果结果中开头和结尾有,的话去掉String string = str.replaceAll("\\d+", ",").replaceAll("^,|,$", "");System.out.println(string); //hello,world,java,mysqlString str1 = "12345";//判断str字符串中是否全部有数字组成,即有1-n个数字组成boolean matches = str1.matches("\\d+");System.out.println(matches); //trueString tel = "0571-4534289";//判断这是否是一个杭州的固定电话boolean result = tel.matches("0571-\\d{7,8}");System.out.println(result);//trueString str2 = "hello|world|java";String[] strs = str2.split("\\|");for (int i = 0; i < strs.length; i++) {System.out.println(strs[i]);/** helloworldjava*/}System.out.println();String str3 = "hello.world.java";String[] strs3 = str3.split("\\.");for (int i = 0; i < strs3.length; i++) {System.out.println(strs3[i]);// hello//world//java}String string4 = "http://www.Bai#du.cn.com?key=123";string4 = string4.toLowerCase();  System.out.println("换大小写"+string4);//http://www.bai#du.cn.com?key=123int a = string4.indexOf("w");string4 =string4.substring(a, string4.lastIndexOf("m")+1);string4.replace("#"," " );System.out.println(string4);
//      String[] strings =string4.split("[^www.baidu.com]");
//     for(String s :strings) {//         System.out.print(s);
//     }}}
}

正则表达式扩展:正则表达式

String类与其他结构之间的转换

import java.io.UnsupportedEncodingException;
import java.util.Arrays;/*** @Description: $ 涉及到String类与其他之间的转换* @Author: dyq* @Date: $*/
public class StringTest4 {public static void main(String[] args) throws UnsupportedEncodingException {//        String与基本数据类型,包装类型之间的转换
//        String -->基本数据类型、包装类;调用包装类的静态方法: parsexxx(str)
//        基本数据类型、包装类-->String:调用String重载的valueof(xxx)String st1 ="123";int num = Integer.parseInt(st1);  //string 转 intString st2 = String.valueOf(num);  //int 转 string//        String 与char[]之间的转换String s = "abc123";char[] chars = s.toCharArray();for (int i =0;i<chars.length;i++){System.out.print(chars[i]+"\t");}char[] arr = new char[]{'h','e','l','l','o'};String s1 = new String(arr);System.out.println(s1);//   String 与byte[]之间的转换
//        编码:String --> byte[]:调用String的igetBytes()
//        解码: byte[--> string:调用String的构造器//        编码:字符串-->字节(看得懂--->看不懂的二进制数据)
//        解码:编码的逆过程,字节-->字符串(看不懂的二进制数据---》看得懂)//        说明:解码时,要求解码使用的字符集必须与编码时使用的字符集一致,否则会出现乱码。String s2 ="javaTest爱你哟";byte[] bytes = s2.getBytes(); //使用默认的字符集,进行转换System.out.println(Arrays.toString(bytes));byte[] gbks = s2.getBytes("gbk");System.out.println(Arrays.toString(gbks));System.out.println("*********************");String s3 = new String(bytes); //使用默认的字符集,进行解码System.out.println(s3);String s4 = new String(gbks);System.out.println(s4);  //出现乱码,原因:编码集合解码集不一致!String str4 =new String(gbks,"gbk");System.out.println(str4);//没有出现乱码}
}


import java.io.UnsupportedEncodingException;
import java.util.Arrays;/*** @Description: $ 涉及到String类与其他结构之间的转换* @Author: dyq* @Date: $*/
public class StringTest4 {public static void main(String[] args) throws UnsupportedEncodingException {//        String与基本数据类型,包装类型之间的转换
//        String -->基本数据类型、包装类;调用包装类的静态方法: parsexxx(str)
//        基本数据类型、包装类-->String:调用String重载的valueof(xxx)String st1 ="123";int num = Integer.parseInt(st1);  //string 转 intString st2 = String.valueOf(num);  //int 转 string//        String 与char[]之间的转换String s = "abc123";char[] chars = s.toCharArray();for (int i =0;i<chars.length;i++){System.out.print(chars[i]+"\t");}char[] arr = new char[]{'h','e','l','l','o'};String s1 = new String(arr);System.out.println(s1);//   String 与byte[]之间的转换
//        编码:String --> byte[]:调用String的igetBytes()
//        解码: byte[--> string:调用String的构造器//        编码:字符串-->字节(看得懂--->看不懂的二进制数据)
//        解码:编码的逆过程,字节-->字符串(看不懂的二进制数据---》看得懂)//        说明:解码时,要求解码使用的字符集必须与编码时使用的字符集一致,否则会出现乱码。String s2 ="javaTest爱你哟";byte[] bytes = s2.getBytes(); //使用默认的字符集,进行转换System.out.println(Arrays.toString(bytes));byte[] gbks = s2.getBytes("gbk");System.out.println(Arrays.toString(gbks));System.out.println("*********************");String s3 = new String(bytes); //使用默认的字符集,进行解码System.out.println(s3);String s4 = new String(gbks);System.out.println(s4);  //出现乱码,原因:编码集合解码集不一致!String str4 =new String(gbks,"gbk");System.out.println(str4);//没有出现乱码}
}

3、StringBuffer



StringBuffer类的常用方法

方法 解析
StringBuffer append(xxx): 提供了很多的append()方法,用于进行字符串拼接
StringBuffer delete(int start,int end): 删除指定位置的内容
StringBuffer replace(int start, int end, String str): 把[start,end)位置替换为strv
StringBuffer insert(int offset, xxx): 在指定位置插入xxx
StringBuffer reverse() : 把当前字符序列逆转


4、StringBuilder

import org.junit.Test;/*** @Description: String. StringBuffer、 StringBuilder三者的异同?* string:不可变的字符序列;底层使用char[]存储* stringBuffer:可变的字符序列;线程安全的,效率低。底层使用char[]存储* StringBuilder: 可变的字符序列;jdk5.0 新增的,线程不安全,效率高;底层使用char[]存储               $** 源码分析:* string str = new String(); // char[ ] value = new char[e];* string str1 = new string("abc" );// char[] value = new char[]i ' a ' , 'b ' , ' c '];** stringBuffer sb1 = new StringBuffer(); //char[] value = new char[16];底层创建了一个长度颊* stringBuffer创建源码,所以声明出一个长度为16的数组。* //public StringBuffer(String str) {*         super(str.length() + 16);*         append(str);*     }* //* System.out.println(sb1.length()); //0* sb1.append( 'a'); //value[e] = 'a';* sb1 .append( 'b');//value[1] = 'b' ;** StringBuffer sb2 = new StringBuffer("abc"); //char[] value = new char[ "abc ".Length()+ 16];** //问题1.System.out.println( sb2.Length());//3*问题2.扩容问题:如果要添加的数据底层数组盛不下了,那就需要扩容底层的数组。* 默认情况下,扩容为原来容量的2倍+2,同时将原有数组中的元素复制到新的数组中。* private void ensureCapacityInternal(int minimumCapacity) {*         // overflow-conscious code*         if (minimumCapacity - value.length > 0) {*             value = Arrays.copyOf(value,*                     newCapacity(minimumCapacity));*         }*     }*     指导意义:开发中建议大家使用:StringBuffer(int capacity)或 StringBuiller(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();* *遍历:for() +charAt() / toString()** @Author: dyq* @Date: $*/
public class StringBufferStringBuilder {@Testpublic  void  test1(){StringBuffer stringBuffer = new StringBuffer("abc");stringBuffer.append('o');  //字符串拼接System.out.println(stringBuffer);//abcostringBuffer.setCharAt(1,'p'); //字符串替换System.out.println(stringBuffer); //apcoSystem.out.println(stringBuffer.length());//字符串长度  4//substring(int start, int end)//返回一个新的 String ,其中包含当前包含在此序列中的字符的子序列。String a =stringBuffer.substring(1,2);System.out.println(a); //pstringBuffer.delete(1,2); //删除字符串System.out.println(stringBuffer);  //aco//appendCodePoint(int codePoint)//将 codePoint参数的字符串表示形式追加到此序列。int str=65;  //AstringBuffer.appendCodePoint(str);System.out.println(stringBuffer); //acoA//public int capacity()//返回当前容量。 容量是新插入字符可用的存储量,超出该容量将进行分配。int b=stringBuffer.capacity();System.out.println(b);//将 str数组参数的子数组的字符串表示形式插入此序列中。stringBuffer.insert(stringBuffer.length(),"啊!美女!");System.out.println(stringBuffer);  //acoA啊!美女!//导致此字符序列被序列的反向替换。stringBuffer.reverse();System.out.println(stringBuffer); //!女美!啊Aoca//从指定的索引处开始,返回指定子字符串第一次出现的字符串中的索引。String str1 ="c";int c= stringBuffer.indexOf(str1,0);System.out.println(c);  //7String str2 ="a";//返回指定索引处的char值。索引的范围是0--length()-1。// 序列的第一个char值在索引的0处,第二个在索引1处,以此类推,这类似于数组索引。char d= stringBuffer.charAt(7);System.out.println(d);  //c}//对比String. StringBuffer、 StringBuiLder三者的效率:// 从高到低排列:StringBuilder > StringBuffer > string@Testpublic  void  test2(){//初始化设置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));}/*StringBuffer的执行时间:4StringBuilder的执行时间:3String的执行时间:957* */
}

饭后甜点:

public class strTest {public static void main(String[] args) {String a="123";String b ="123";String c=new String("123");String d = new String("123");System.out.println(a.equals(b)); //true  System.out.println(a==b);//true  地址值一样System.out.println(c.equals(b)); //trueSystem.out.println(c==d);//false   地址值不一样System.out.println(a.equals(c));//trueSystem.out.println(a==c);//false  地址值不一样}
}

与StringBuffer、StringBuilder之间的转换
String -->StringBuffer、StringBuilder:调用stringBuffer、stringBuilder构造器
StringBuffer、StringBuilder -->①String : 调用string构造器; ②StringBuffer、StringBuilder的tostring()

JVM中字符串常量池存放位置说明:
jdk 1.6 (jdk 6.e ,java 6.0):字符串常量池存储在方法区〈永久区>
jdk 1.7:字符串常量池存储在堆空间
jdk 1.8:字符串常量池存储在方法区(元空间)

二、JDK 8之前的日期时间API

1、System

2、Date类

import java.util.Date;
/*** @Description: JDK 8之前日期和时间的AP工测试* @Author: dyq* @Date: $*/
public class DateTest {@Testpublic  void  test1(){long time = System.currentTimeMillis();//返回1970年1月1日0时0分0秒之间以毫秒为单位的时间差。System.out.println(time);}/*java.util.Date类/---java.sqLDate类1.两个构造器的使用2.两个方法的使用>tostring(():显示当前的年、月、日、时、分、秒>getTime():获取当前Date对象对应的时间戳3. java.sql. Date对应着数据库中的日期类型的变量>如何实例化>如何将util.Date对象zhaur*/@Testpublic  void  test2(){//构造器一:Date():创建一个对应当前时间的Date对象Date date = new Date();System.out.println(date.toString()); //Wed Apr 28 11:55:31 CST 2021System.out.println(date.toInstant()); //2021-04-28T03:55:31.164ZSystem.out.println(date.getTime());  //毫秒数//构造器二:创建指定毫秒数的Date对斜Date date1 = new Date(161958220726L);System.out.println(date1.toString());//创建java。sql.Date对象java.sql.Date date2 = new java.sql.Date(67483472943L);System.out.println(date2); //1972-02-21//如何将java.util.Ddte对象转换为java.sqL.Date对象Date date3 = new java.sql.Date(67483472943L);java.sql.Date date4 = (java.sql.Date) date3;System.out.println(date4);}
}

3、SimpleDateFormat


4、Calendar

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;/*** jdk 8之前的日期时间的AP工测试* 1. System类中currentTimeMiLlis();* 2. java.util.Date和子类java.sql.Date.* 3.SimpLeDateFormat* 4. calendar*/
public class DateTimeTest {@Testpublic  void  Test() 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 = "21-04-30 下午4:29";  //默认行为Date date1 = sdf.parse(str);System.out.println(date1);SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");String format1 = sdf1.format(date);System.out.println(format1); //2021-04-28 04:49:00//解析:要求字符串必须是符合SimpleDateFormat识别的格式(通过构造器参数体现)Date parse = sdf1.parse("2021-04-28 04:49:00");System.out.println(parse);}//    练习一:字符串"2020-09-08"转换为java.sqL. Date@Testpublic void testExer() throws ParseException{String birth = "2020-09-08" ;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);}//    练习二:“三天打渔两天晒网”1990-e1-01xXXX-XX-x×打渔?晒网?
//    举例: 2020-09-08 ?总天数
//    总天数% 5 == 1,2,3
//    打渔总天数% 5 == 4,0 :晒网//    总天数的计算?
//    方式一:(date2.getTime( )-date1.getTime())/(1000* 60*60*24)+1
//    方式二:1990-01-01 -->2019-12-31 +   2020-01-01 -->2020-09-08@Testpublic void  Test3(){String date ="2021-09-01";}/*Calencar日历类的使用* */@Testpublic  void  testCalendar(){//实例化Calendar calendar = Calendar.getInstance();
// 从一个 Calendar 对象中获取 Date 对象Date date = calendar.getTime();
// 使用给定的 Date 设置此 Calendar 的时间date = new Date(234234235235L);calendar.setTime(date);calendar.set(Calendar.DAY_OF_MONTH, 8);System.out.println("当前时间日设置为8后,时间是:" + calendar.getTime());calendar.add(Calendar.HOUR, 2);System.out.println("当前时间加2小时后,时间是:" + calendar.getTime());calendar.add(Calendar.MONTH, -2);System.out.println("当前日期减2个月后,时间是:" + calendar.getTime());}
}

三、JDK8中新日期时间API

1、新日期时间API出现的背景



2、LocalDate、LocalTime、LocalDateTime



3、 瞬时:Instant

代码测试:

import org.junit.Test;
import java.sql.Date;
import java.time.*;/*** @Description: $* @Author: dyq* @Date: $*/
public class JDK8DateTimeTest {@Testpublic  void  TestDate(){//偏移性:Date中的年份是从1900开始的,而月份都从0开始。Date data = new Date(2020-1900,9-1,8);System.out.println(data); //2020-09-08}//    LocalDate、LocalTime、LocalDateTime@Testpublic  void  TestDate1(){//now():获取当前日期,时间,日期+时间
//         说明://1.LocalDateTime相较于LocaLDate. LocalTime,使用频率要高LocalDate localDate = LocalDate.now();LocalTime localTime = LocalTime.now();LocalDateTime localDateTime = LocalDateTime.now();System.out.println(localDate);//2021-04-29System.out.println(localTime);// 14:14:25.182System.out.println(localDateTime);//2021-04-29T14:14:25.182//of():设置指定的年,月,日,时i, 分,秒。没有偏移量LocalDateTime localDateTime1 =LocalDateTime.of(2021,4,29,23,34,56);System.out.println(localDateTime1);//getXXX():获取相关的属性System.out.println( localDateTime.getDayOfMonth());//这个月的第几天System.out.println(localDateTime.getDayOfWeek());System.out.println(localDateTime.getDayOfYear());System.out.println(localDateTime.getHour());System.out.println(localDateTime.getMinute());//提现不可变性//withXXX():设置相关的属性LocalDate localDate1 = localDate.withDayOfMonth(22);System.out.println(localDate);//2021-04-29System.out.println(localDate1); //2021-04-22LocalDateTime localDateTime2= localDateTime.withHour(4);System.out.println(localDateTime);  //2021-04-29T14:53:03.028System.out.println(localDateTime2);  //2021-04-29T04:53:03.028//不可变性LocalDateTime localDateTime3=localDateTime.plusMonths(3);System.out.println(localDateTime);  //2021-04-29T14:55:01.746System.out.println(localDateTime3); //2021-07-29T14:55:01.746LocalDateTime localDateTime4 = localDateTime.minusDays(6);System.out.println(localDateTime);  //2021-04-29T15:10:41.551System.out.println(localDateTime4);  //2021-04-23T15:10:41.551}/** instant的使用类似于java.util.Date类*/@Testpublic  void  tetsInstant(){Instant instant =Instant.now();System.out.println(instant);//2021-04-29T07:21:53.583Z//OffsetDateTime offsetDateTime=instant.atOffset(ZoneOffset.ofHours(8));System.out.println(offsetDateTime);  //2021-04-29T15:21:53.583+08:00//toEpochMilli():获取自1970年1月1日0时e分e秒(UTC)开始的豪秒数long milli=instant.toEpochMilli();System.out.println(milli);//ofEpochMilli( ):通过给定的毫秒数,获取Instant实例-->Date(Long millis)Instant instant1 =Instant.ofEpochMilli(1619681113946L);System.out.println(instant1);}
}

4、格式化与解析日期或时间 DateTimeFormatter

5、其它API


代码测试用例:

import org.junit.Test;import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.util.Set;/*** @Description: $* @Author: dyq* @Date: $*/
public class DateTimeFormatterTest {@Testpublic  void  test(){//方式一:预定义的标准格式:DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;//格式化LocalDateTime localDateTime=LocalDateTime.now();String str1=formatter.format(localDateTime);System.out.println(localDateTime); //2021-04-29T15:36:41.727System.out.println(str1);//2021-04-29T15:36:41.727//解析:字符串--》日期TemporalAccessor parse= formatter.parse("2021-04-29T15:36:41.727");System.out.println(parse);//方式二:// 本地化相关的格式。// 如: ofLocalizedDateTimle( FormatStyLe.LONG)DateTimeFormatter formatter1 =DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);String str2 = formatter1.format(localDateTime);System.out.println(str2); //2021年4月29日 下午03时46分35秒//本地化相关的格式。如: ofLocalizedDate()//   FormatSstyle.FULL / FormatStyLe.LONG / FormatStyLe.NEDTU / FormatStyLe.SHORT:适用于lLocalDateDateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);String str3 = formatter2.format(LocalDate.now());System.out.println(str3); //2021年4月29日 星期四DateTimeFormatter formatter3 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);String str4 = formatter3.format(LocalDate.now());System.out.println(str4); //2021年4月29日//重点: 方式三:自定义的格式。如: ofPattern("yyyy-MM-dd hh : mm : ss E")DateTimeFormatter formatter4 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");//格式化String str5 =formatter4.format(LocalDateTime.now());System.out.println(str5); //2021-04-29 03:53:15//解析TemporalAccessor accesso= formatter4.parse("2021-04-29 03:53:15");System.out.println(accesso);//{SecondOfMinute=15, HourOfAmPm=3, MicroOfSecond=0, MinuteOfHour=53, NanoOfSecond=0, MilliOfSecond=0},ISO resolved to 2021-04-29}@Testpublic  void  Test(){//ZoneId:类中包含了所有的时区信息
// ZoneId的getAvailableZoneIds():获取所有的ZoneIdSet<String> zoneIds = ZoneId.getAvailableZoneIds();for (String s : zoneIds) {System.out.println(s);}
// ZoneId的of():获取指定时区的时间LocalDateTime localDateTime = LocalDateTime.now(ZoneId.of("Asia/Tokyo"));System.out.println(localDateTime);
//ZonedDateTime:带时区的日期时间
// ZonedDateTime的now():获取本时区的ZonedDateTime对象ZonedDateTime zonedDateTime = ZonedDateTime.now();System.out.println(zonedDateTime);
// ZonedDateTime的now(ZoneId id):获取指定时区的ZonedDateTime对象ZonedDateTime zonedDateTime1 = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));System.out.println(zonedDateTime1);}@Testpublic  void  Test1() {//Duration:用于计算两个“时间”间隔,以秒和纳秒为基准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());}@Testpublic  void  Test2() {//Period:用于计算两个“日期”间隔,以年、月、日衡量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);}@Testpublic  void  Test3(){// TemporalAdjuster:时间校正器// 获取当前日期的下一个周日是哪天?TemporalAdjuster temporalAdjuster = TemporalAdjusters.next(DayOfWeek.SUNDAY);LocalDateTime localDateTime = LocalDateTime.now().with(temporalAdjuster);System.out.println(localDateTime);// 获取下一个工作日是哪天?LocalDate localDate = LocalDate.now().with(new TemporalAdjuster() {@Overridepublic 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);}
}

6、参考:与传统日期处理的转换

四、Java比较器

在Java中经常会涉及到对象数组的排序问题,那么就涉及到对象之间的比较问题。

Java实现对象排序的方式有两种:

  • 自然排序:java.lang.Comparable
  • 定制排序:java.util.Comparator

1、方式一:自然排序:java.lang.Comparable(comparable接口)


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;}@Overridepublic String toString() {return "Goods{" +"name='" + name + '\'' +", price=" + price +'}';}//指明商品比较大小的方式@Overridepublic 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("传入的数据类型不一致!");}
}
public class ComparableTest {/*Comparable接口的使用举例Comparable接口的使用举例:自然排HI1.像String、包装类等实现了Comparable接口,重写了compareTo(obj)方法,给出了比较两个对象2.像String、包装类重写compareTo()方法以后,进行了从小到大的排列3.重写compareTo(obj)的规则:如果当前对象this大于形参对象obj,则返回正整数,如果当前对象this小于形参对象obj,则返回负整数,如果当前对象this等于形参对象obj,则返回零。4.对于自定义类来说,如果需要排序,我们可以让自定义类实现Comparable接口,重写compareTo(
在compareTo(obj)方法中指明如何排序* */@Testpublic  void  Test1(){String[] arr = new String[]{"AA","PP","CC","BB","SS","DD","FF","JJ","KK"};Arrays.sort(arr);System.out.println(Arrays.toString(arr)); //[AA, BB, CC, DD, FF, JJ, KK, PP, SS]}@Testpublic  void Test2(){Goods[] arr = new Goods[4];arr[0]=new Goods("联想",34);arr[1]=new Goods("华为",44);arr[2]=new Goods("戴尔",50);arr[3]=new Goods("宏碁",24);Arrays.sort(arr);System.out.println(Arrays.toString(arr));//[Goods{name='宏碁', price=24.0}, Goods{name='联想', price=34.0},// Goods{name='华为', price=44.0}, Goods{name='戴尔', price=50.0}]}
}

2、方式二:定制排序:java.util.Comparator(Comparator接口)

    @Testpublic void Test3() {String[] arr = new String[]{"AA", "PP", "CC", "BB", "SS", "DD", "FF", "JJ", "KK"};Arrays.sort(arr, new Comparator() {@Overridepublic 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);}throw new RuntimeException("传入的数据类型不一致!");}});System.out.println(Arrays.toString(arr)); //[SS, PP, KK, JJ, FF, DD, CC, BB, AA]}

五、System类

  • System类代表系统,系统级的很多属性和控制方法都放置在该类的内部。 该类位于java.lang包。
  • 由于该类的构造器是private的,所以无法创建该类的对象,也就是无法实
    例化该类。其内部的成员变量和成员方法都是static的,所以也可以很方便 的进行调用。
  • 成员变量
  • System类内部包含in、out和err三个成员变量,分别代表标准输入流
    (键盘输入),标准输出流(显示器)和标准错误输出流(显示器)。
  • 成员方法
  • native long currentTimeMillis():
    • 该方法的作用是返回当前的计算机时间,时间的表达格式为当前计算机时
      间和GMT时间(格林威治时间)1970年1月1号0时0分0秒所差的毫秒数。
  • void exit(int status):
    • 该方法的作用是退出程序。其中status的值为0代表正常退出,非零代表 异常退出。使用该方法可以在图形界面编程中实现程序的退出功能等。
  • void gc():
    该方法的作用是请求系统进行垃圾回收。至于系统是否立刻回收,则
    取决于系统中垃圾回收算法的实现以及系统执行时的情况。
  • String getProperty(String key):
    • 该方法的作用是获得系统中属性名为key的属性对应的值。

系统中常见 的属性名以及属性的作用如下表所示:

public class SystemTest {@Testpublic void  Test(){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类

七、BigInteger与BigDecimal

1、BigInteger类


2、BigDecimal类

 @Testpublic void testBigInteger() {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));}
12433241123
1130.486
1130.486454545454545

java 中常用的类(笔记 十六)相关推荐

  1. java 中常用的类

    java 中常用的类 Math Math 类,包含用于执行基本数学运算的方法 常用API 取整 l  static double abs(double  a) 获取double 的绝对值 l  sta ...

  2. Java中常用的类,包,接口

    Java中常用的类,包,接口 包名 说明 java.lang 该包提供了Java编程的基础类,例如 Object.Math.String.StringBuffer.System.Thread等,不使用 ...

  3. Java中常用的类及其特点

    Java中的内部类有四种(内部类作用1.封装装类型. 2.直接访问外部类成员. 3.回调.)内部类,方便他们的外部类调用,一般不会被其它类使用,比如事件监听器之类的,外部类刚好继承了一个别的类,如果你 ...

  4. java中常用的包、类、以及包中常用的类、方法、属性----sql和text\swing

    java中常用的包.类.以及包中常用的类.方法.属性 常用的包 java.io.*; java.util.*; java.lang.*; java.sql.*; java.text.*; java.a ...

  5. java中常用API、Scanner类、匿名对象、Random类、ArrayList类、对象数组

    java中常用API: API:Application Programming Interface,应用程序编程接口.Java API是JDK中提供给我们使用的类的说明文档.这些类将底层的代码实现封装 ...

  6. java有哪些类_Java中常用的类有哪些?

    展开全部 一. System: 1.     首先是System类,因为从一开始从接触java起,我32313133353236313431303231363533e58685e5aeb9313333 ...

  7. JAVA语言异常_Java语言中常用异常类EoFException是用来处理( )异常的类_学小易找答案...

    [填空题]Java语言中常用异常类ClassNotFoundException是用来处理 ( )的异常的类 [填空题]Java语言声明 ( ) 类为会产生"严重错误"的类 [简答题 ...

  8. java中常用的工具类(二)FtpUtil, 汉字转拼音,zip工具类,CollectionUtil,MathUtil,

    下面继续分享java中常用的一些工具类,希望给大家带来帮助! 1.FtpUtil Java package com.itjh.javaUtil;import java.io.File; import ...

  9. java中常用的日期工具类

    java中常用的日期工具类 日期相关的类: package net.yto.ofclacct.core.util;import java.text.ParseException; import jav ...

最新文章

  1. Windows Phone 7 Tip (5) -- App liftcycle
  2. 【转】【C++】__stdcall、__cdcel和__fastcall三者的区别
  3. [云炬python3玩转机器学习]4-7机器学习算法训练和测试样本集数据同时归一化
  4. Sqlserver数据库的恢复
  5. DBus glib 各数据类型接收与发送详解—C语言(3)
  6. 复地邮箱服务器地址,打印服务器设置方法
  7. 吊炸天!一行命令快速部署大规模K8S集群!!!
  8. opencv画框返回坐标 python_20行Python代码实现视频字符化
  9. 从富文本中截取图片_JS 获取富文本中的第一张图片 (正则表达式)
  10. 清华大学人工智能研究院知识中心成立仪式隆重举行,发布知识计算开放平台...
  11. 怎样学好python编程-怎样学习python编程?
  12. 30. 确保目标空间足够大
  13. Rust: 属性(attribute)的含义及文档大全
  14. 未来教育python软件_未来教育考试系统
  15. FireBase Android版本测试
  16. 国际道教协会黄世真道长为《中华辟谷养生》题写序言!
  17. 玩世不恭----准备篇
  18. 西南交大计算机应用基础 第2次作业 主观题目,西南交大网络教育2011-2012学年计算机应用基础第四次作业(主观题)...
  19. 【计网】(一) 集线器、网桥、交换机、路由器等概念
  20. python重新安装ssl_python3安装文件遇到ssl未安装问题

热门文章

  1. 如何保持浏览器能同时登录多个账户
  2. 接口测试用例编写方法
  3. Python面向对象之私有化属性
  4. 一种清洁机器人设计及仿真
  5. 【Python数据处理】数据降维
  6. ERROR SparkContext: Error initializing SparkContext. java.lang.IllegalArgumentException: System memo
  7. JS 正则匹配(RegExp)
  8. 微信小程序——数组操作 (增加删除修改遍历)map、filter、forEach、find的用法、二维数组,排序,求和、指定长度数组赋值
  9. 微信小程序数组删除元素splice不起作用
  10. 不能锁定计算机怎么搞,怎么样锁定电脑,或者使电脑不能联网~