【Java】7.3 基本類 & 7.4 Java 8 的日期、時間類

目錄

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()-1
        System.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位置插入str
        System.out.println(stringBuffer.insert(2,"☆"));
        //輸出:!d☆lrow olleH Hello Sun!130

        //void setCharAt(index,ch):字符替換,將第index個字符替換爲ch
        stringBuffer.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類:生成僞隨機數

  • 提供nextXxx()方法:生成隨機數

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.06
        0.05 - 0.01 = 0.04
        0.05 * 0.01 = 0.0005
        0.05 / 0.01 = 5
        ==========使用Double作爲BigDecimal構造器參數===========
        0.05 + 0.01 = 0.06000000000000000277555756156289135105907917022705078125
        0.05 - 0.01 = 0.04000000000000000277555756156289135105907917022705078125
        0.05 * 0.01 = 0.0005000000000000000277555756156289135105907917022705078125
        0.05 / 0.01 = 5.000000000000000277555756156289135105907917022705078125
         *  */
    }
}

valueOf(obj):把數字類型變爲字符型

XxxValue():把字符型變爲數字類型

//防止一個類的實例化
private 類名(){}

 Java 8 新增的日期、時間包

【提供的類和方法】

  • Clock類
  1. instant():代表具體時刻,精確到納秒
  2. millis():對應的精確到毫秒
  • Duration類
  1. ofSecond(int)、toMinutes():int秒轉爲分鐘
  2. offset(clock,int):在時間clock的家畜上在上int分鐘
  • Instant類
  1. Instant.now():獲取當前時間
  2. plusSecond(int):將對象增加int秒
  3. parse(String):用字符串解析Instant對象,格式:parse("2018-02-23T10:22:35.032Z")
  4. plus(Duration.ofHour().plusMinutes):在原基礎上增加X小時xx分鐘
  5. minus(Duration):在原基礎上減去X小時xx分鐘
  • LocalDate類
  1. LocalDate.now():獲取當前時間
  2. ofYearDay(year,index):輸出year的index天
  3. of(Year,Month,Day):設置年月日
  • LocalTime類
  1. LocalTime.now():獲取當前時間
  2. of(hours,minutes):設置爲幾點幾分
  3. ofSecondOfDay(index):返回一天中的第index秒
  • localDateTime類
  1. localDateTime.now():獲取當前時間
  2. 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的用法=========");
        //獲取當前Clock
        Clock 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秒,返回新的Clock
        Clock 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秒,返回新的instant
        Instant 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-1
        localDate = 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);
        //根據指定月份獲取YearMonth
        YearMonth 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);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章