【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);
    }
}

 

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