目錄
String、StringBuffer和StringBuilder類
Rondom類
?BigDecimal類
?Java 8?新增的日期、時間包
String、StringBuffer和StringBuilder類
【三者的介紹】
- String類:不可變字符串類,從創立到銷毀整個生命周期字符序列不可改變
- StringBuffer類:字符序列可變的字符串。提供:append()、insert()、reverse()、setChar()、setLength()等方法
- StringBuilder類:StringBuild類與StringBuffer類基本相似。不同的是,StringBuffer是線程安全。而StringBuilder無實現線程安全功能,性能略高。(在通常情況下有限選用StringBuilder類)
【String類】
String類提供的方法
- char charAt(index) : 從0~length()-1,返回地index+1個字符
- int compareTo(String) : 比較兩個字符串的大小,若相等,則返回0;若不相等返回'h'-'w',即兩個字符串第一個不一樣的字符ASCII碼相減的值
- boolean equals(obj) : 兩個字符串是否相同
- String substring(start,end) : 開始,結束截取片段
- String toLowerCase() : 將字符串轉為小寫
- String toUpperCase() : 將字符串轉為大寫
【代碼實例】
/*** @ClassName: StringTest* @description:String類的方法使用* @author: FFIDEAL* @Date: 2020/3/7 17:28*/public class StringTest {public static void main(String[] args){String str1 = new String("Hello ");String str2 = new String("World!");String str3 = new String("Hello ");//char charAt(index):從0~length()-1System.out.println("str1的第3個字符是:"+str1.charAt(2));//輸出:l//int compareTo(String):比較兩個字符串的大小,若相等,則返回0;若不相等返回'h'-'w'//第一個不一樣的字符ASCII碼相減的值System.out.println(str1.compareTo(str2));System.out.println(str1.compareTo(str3));//輸出:0//-15//boolean equals(obj):兩個字符串是否相同System.out.println(str1.equals(str2));System.out.println(str1.equals(str3));/*輸出:* false* true* *///int indexOf():查找某個字符串第一次出現的位置System.out.println(str1.indexOf('l'));System.out.println(str1.indexOf('l',1));/*輸出:* 2* 2* *///String substring(start,end):開始,結束截取片段System.out.println(str1.substring(1,3));//String toLowerCase():將字符串轉為小寫System.out.println(str1.toLowerCase());//String toUpperCase():將字符串轉為大寫System.out.println(str1.toUpperCase());}
}
【StringBuffer類】
StringBuffer類提供的方法
- StringBuffer reverse()?: 將字符串反轉,這是對對象的修改
- StringBuffer append(obj) : 追加,參數依附在調用字符串之后
- StringBuffer insert(offset,str) : 插入,在offset位置插入str
- void setCharAt(index,ch) : 字符替換,將第index個字符替換為ch
- void replace(start,end,str) : 字符串替換
- void delete(start,end) : 刪除,區間左閉右開
- void setLength(int) : 改變StringBuffer長度,只保留前面的字符串
- int length() : 字符串長度
- int capacity() : 規定的StringBuffer初始容量
/*** @ClassName: StringBufferTest* @description:StringBuffer類的方法使用* @author: FFIDEAL* @Date: 2020/3/6 19:07*/public class StringBufferTest {public static void main(String[] args){StringBuffer stringBuffer = new StringBuffer("Hello world!");//StringBuffer reverse():將字符串反轉,這是對對象的修改StringBuffer stringBufferReverse = stringBuffer.reverse();System.out.println(stringBufferReverse);//輸出:!dlrow olleH//StringBuffer append(obj):追加,參數依附在調用字符串之后//stringBuffer2.append第一次調用時stringBuffer變為了!dlrow olleH Hello Sun!//第二次調用append時,stringBuffer變為!dlrow olleH Hello Sun!130, 因為都依附在stringBuffer之后的System.out.println(stringBuffer.append(" Hello Sun!"));//輸出:!dlrow olleH Hello Sun!System.out.println(stringBuffer.append(130));//輸出:!dlrow olleH Hello Sun!130//StringBuffer insert(offset,str):插入,在offset位置插入strSystem.out.println(stringBuffer.insert(2,"☆"));//輸出:!d☆lrow olleH Hello Sun!130//void setCharAt(index,ch):字符替換,將第index個字符替換為chstringBuffer.setCharAt(0,'△');System.out.println(stringBuffer);//輸出:△d☆lrow olleH Hello Sun!130//void replace(start,end,str):字符串替換stringBuffer.replace(5,6," replace替換方式 " );System.out.println(stringBuffer);//輸出:△d☆lr replace替換方式 w olleH Hello Sun!130//void delete(start,end):刪除,區間左閉右開stringBuffer.delete(0,1);System.out.println(stringBuffer);//輸出:d☆lr replace替換方式 w olleH Hello Sun!130//void setLength(int):改變StringBuffer長度,只保留前面的字符串stringBuffer.setLength(5);System.out.println(stringBuffer);//輸出△d☆lr//字符串長度System.out.println(stringBuffer.length());//規定的StringBuffer初始容量System.out.println(stringBuffer.capacity());}
}
【StringBuilder類】
與StringBuffer是一樣的,不同的是StringBuffer是線程安全的
Rondom類
Rondom類:生成偽隨機數
ThreadLocalRandom類:多線程下使用生成隨機數的
- 提供nextXxx(start,end)方法:在[start,end)范圍內生成隨機數
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;/*** @ClassName: RandomTest* @description: Random類是一種偽隨機類* 說它偽隨機類的因為只要兩個Random對象的種子一致,* 且方法調用也一致,他們就是闡述相同的數字序列* @author: FFIDEAL* @Date: 2020/3/8 16:38*/public class RandomTest {public static void main(String[] args){System.out.println("--------第一個種子為50的Random對象----------");Random r1 = new Random(50);System.out.println("r1.nextInt():\t"+r1.nextInt());System.out.println("r1.nextBoolean():\t"+r1.nextBoolean());System.out.println("r1.nextDouble():\t"+r1.nextDouble());System.out.println("r1.nextGaussian():\t"+r1.nextGaussian());System.out.println("r1.nextInt():\t"+r1.nextInt());System.out.println("--------第一個種子為50的Random對象----------");Random r2 = new Random(50);System.out.println("r1.nextInt():\t"+r2.nextInt());System.out.println("r1.nextBoolean():\t"+r2.nextBoolean());System.out.println("r1.nextDouble():\t"+r2.nextDouble());System.out.println("r1.nextGaussian():\t"+r2.nextGaussian());System.out.println("r1.nextInt():\t"+r2.nextInt());System.out.println("--------第一個種子為100的Random對象----------");Random r3 = new Random(100);System.out.println("r1.nextInt():\t"+r3.nextInt());System.out.println("r1.nextBoolean():\t"+r3.nextBoolean());System.out.println("r1.nextDouble():\t"+r3.nextDouble());System.out.println("r1.nextGaussian():\t"+r3.nextGaussian());System.out.println("--------ThreadLocalRandom類----------");//ThreadLocalRandom():多線程下使用生成隨機數的ThreadLocalRandom tlr = ThreadLocalRandom.current();//生成一個4~50之間的偽隨機整數int var1 = tlr.nextInt(4,50);System.out.println("生成一個4~50之間的偽隨機整數:"+var1);//生成一個51~100之間的偽隨機浮點數double var2 = tlr.nextDouble(51.0,100.0);System.out.println("生成一個51~100之間的偽隨機浮點數:"+var2);}
}/*
--------第一個種子為50的Random對象----------
r1.nextInt(): -1160871061
r1.nextBoolean(): true
r1.nextDouble(): 0.6141579720626675
r1.nextGaussian(): 2.377650302287946
r1.nextInt(): -942771064
--------第一個種子為50的Random對象----------
r1.nextInt(): -1160871061
r1.nextBoolean(): true
r1.nextDouble(): 0.6141579720626675
r1.nextGaussian(): 2.377650302287946
r1.nextInt(): -942771064
--------第一個種子為100的Random對象----------
r1.nextInt(): -1193959466
r1.nextBoolean(): true
r1.nextDouble(): 0.19497605734770518
r1.nextGaussian(): 0.6762208162903859
--------ThreadLocalRandom類----------
生成一個4~50之間的偽隨機整數:16
生成一個51~100之間的偽隨機浮點數:96.30652015127957
*/
?BigDecimal類
要求精度較高的時候使用,在使用時一定要使用String對象作為操作數
import java.math.BigDecimal;/*** @ClassName: BigDecimalTest* @description: BigDecimal類就是能更精確表示、計算浮點數* 由以下代碼得知要用String對象作為構造器參數精準度更高* 此外,當我們最后還需要用double類型時,不妨做一個工具類* return b1.add(b2).doubleValue();將double→(使用BigDecimal類)String→double* @author: FFIDEAL* @Date: 2020/3/8 18:29*/public class BigDecimalTest {public static void main(String[] args){BigDecimal f1 = new BigDecimal("0.05");BigDecimal f2 = BigDecimal.valueOf(0.01);BigDecimal f3 = new BigDecimal(0.05);System.out.println("==========使用String作為BigDecimal構造器參數===========");System.out.println("0.05 + 0.01 = " + f1.add(f2));System.out.println("0.05 - 0.01 = " + f1.subtract(f2));System.out.println("0.05 * 0.01 = " + f1.multiply(f2));System.out.println("0.05 / 0.01 = " + f1.divide(f2));System.out.println("==========使用Double作為BigDecimal構造器參數===========");System.out.println("0.05 + 0.01 = " + f3.add(f2));System.out.println("0.05 - 0.01 = " + f3.subtract(f2));System.out.println("0.05 * 0.01 = " + f3.multiply(f2));System.out.println("0.05 / 0.01 = " + f3.divide(f2));/*輸出:==========使用String作為BigDecimal構造器參數===========0.05 + 0.01 = 0.060.05 - 0.01 = 0.040.05 * 0.01 = 0.00050.05 / 0.01 = 5==========使用Double作為BigDecimal構造器參數===========0.05 + 0.01 = 0.060000000000000002775557561562891351059079170227050781250.05 - 0.01 = 0.040000000000000002775557561562891351059079170227050781250.05 * 0.01 = 0.00050000000000000002775557561562891351059079170227050781250.05 / 0.01 = 5.000000000000000277555756156289135105907917022705078125* */}
}
valueOf(obj):把數字類型變為字符型
XxxValue():把字符型變為數字類型
//防止一個類的實例化
private 類名(){}
?Java 8?新增的日期、時間包
【提供的類和方法】
instant():代表具體時刻,精確到納秒millis():對應的精確到毫秒
ofSecond(int)、toMinutes():int秒轉為分鐘offset(clock,int):在時間clock的家畜上在上int分鐘
Instant.now():獲取當前時間plusSecond(int):將對象增加int秒parse(String):用字符串解析Instant對象,格式:parse("2018-02-23T10:22:35.032Z")plus(Duration.ofHour().plusMinutes):在原基礎上增加X小時xx分鐘minus(Duration):在原基礎上減去X小時xx分鐘
LocalDate.now():獲取當前時間ofYearDay(year,index):輸出year的index天of(Year,Month,Day):設置年月日
LocalTime.now():獲取當前時間of(hours,minutes):設置為幾點幾分ofSecondOfDay(index):返回一天中的第index秒
localDateTime.now():獲取當前時間localDateTime.plusHours(hours).plusMinutes(minutes):在當前時間是加上hours小時minutes分鐘
import java.time.*;/*** @ClassName: NewDateTest* @description: java 8 新增的日期時間包* @author: FFIDEAL* @Date: 2020/3/8 22:24*/public class NewDateTest {public static void main(String[] args){System.out.println("========以下是Clock的用法=========");//獲取當前ClockClock clock = Clock.systemUTC();//通過Clock獲取當前時刻,instant():代表一個具體的時刻,精確到納秒System.out.println("當前時刻為:" + clock.instant());//獲取clock對應的毫秒數,與System.currentTimeMillis()輸出相同System.out.println(clock.millis());System.out.println(System.currentTimeMillis());System.out.println("========以下是Duration的用法=========");Duration d = Duration.ofSeconds(6000);System.out.println("6000秒相當于" + d.toMinutes() + "分鐘");System.out.println("6000秒相當于" + d.toHours() + "小時");System.out.println("6000秒相當于" + d.toDays() + "天");//在clock的基礎上增加6000秒,返回新的ClockClock clock2 = Clock.offset(clock,d);//可以看到clock和clock2相差了1小時40分鐘System.out.println("當前時刻加6000秒為:" + clock2.instant());System.out.println("========以下是Instant的用法=========");//獲取當前時間Instant instant = Instant.now();System.out.println(instant);//instant添加6000秒,返回新的instantInstant instant1 = instant.plusSeconds(6000);System.out.println(instant1);//根據字符串解析Instant現象,月和日期都要兩位數,查源碼可得Instant instant2 = Instant.parse("2018-02-23T10:22:35.032Z");System.out.println(instant2);//在instant2上添加5小時40分鐘Instant instant3 = instant2.plus(Duration.ofHours(5).plusMinutes(40));System.out.println(instant3);//獲取instant3的5天前的時刻Instant instant4 = instant3.minus(Duration.ofDays(5));System.out.println(instant4);System.out.println("========以下是LocalDate的用法=========");//獲取當前日期LocalDate localDate = LocalDate.now();System.out.println(localDate);//獲取2020年的第202天localDate = LocalDate.ofYearDay(2020,202);System.out.println(localDate);//設置為2020-10-1localDate = LocalDate.of(2020, Month.OCTOBER,1);System.out.println(localDate);System.out.println("========以下是LocalTime的用法=========");//獲取當前時間LocalTime localTime = LocalTime.now();System.out.println(localTime);//設置為22:33分localTime = LocalTime.of(22,33);System.out.println(localTime);//返回一天中第45245秒localTime = LocalTime.ofSecondOfDay(45245);System.out.println(localTime);System.out.println("========以下是localDateTime的用法=========");//獲取當前的時間和日期LocalDateTime localDateTime = LocalDateTime.now();System.out.println(localDateTime);//在當前日期上加上25小時3分鐘LocalDateTime future = localDateTime.plusHours(25).plusMinutes(3);System.out.println(future);System.out.println("========以下是Year、YearMonth、MonthDay的用法=========");Year year = Year.now();//獲取當前年份System.out.println("當前年份是:" + year);year = year.plusYears(5);System.out.println("當前年份再加5年是:" + year);//根據指定月份獲取YearMonthYearMonth yearMonth = YearMonth.now();//獲取當年年月System.out.println(yearMonth);YearMonth ym = year.atMonth(10);System.out.println("Year年10月:" + ym);//當前年月再加5年減3個月ym = ym.plusYears(5).minusMonths(3);System.out.println("當前年月再加5年減3個月是:" + ym);MonthDay monthDay = MonthDay.now();System.out.println("當前月日" + monthDay);//設置為5月23日MonthDay md = monthDay.with(Month.MAY).withDayOfMonth(23);System.out.println("設置為5月23日:" + md);}
}
?
總結
以上是生活随笔為你收集整理的【Java】7.3 基本类 7.4 Java 8 的日期、时间类的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。