30天搞定Java--day21

每日一考和复习

每日一考

  1. 画出如下几行代码的内容结构:
String s1 = "hello"; 
String s2 = "hello";
String s3 = new String("hello");
s1 += “world”; 

在这里插入图片描述

  1. 如何理解String类的不可变性
String类字符串初始化后进行更改将创造新的字符串,而不是在原有的基础上进行更改
  1. String类是否可以被继承?为什么?
    String s = new String(“hello”);在内存中创建了几个对象?请说明
1.不可被继承,String类为final类型
2.创建了两个对象,一个是在方法区的“hello”另一个是在堆中指向“hello的地址”
  1. String,StringBuffer,StringBuilder三者的对比
1.String和StringBuffer出现比较早,在JDK1.0就已经存在,StringBuilder是JDK1.5之后出现的
2.String是不可变的,StringBuffer和StringBuilder是可变的
3.StringBuffer是线程安全的,StringBuilder是线程不安全的、效率更高
  1. String的常用方法有哪些?(至少7个)
1.length
2.compareTo
3.indexOf
4.startsWith
5.endsWith
6.charAt
7.replace

复习
day20的学习内容

知识补充

String与StringBuffer、StringBuilder之间的转换
String --> StringBuffer、StringBuilder:调用StringBuffer、StringBuilder的构造器
StringBuffer、StringBuilder --> String:①调用String的构造器②调用StringBuffer、StringBuilder的toString方法

Java常用类

JDK 8之前的日期时间API(接day20)

SimpleDateFormat

SimpleDateFormat的使用:SimpleDateFormat对日期Date类的格式化和解析

  1. 两个操作:
    1.1 格式化:日期 —>字符串
    1.2 解析:格式化的逆过程,字符串 —> 日期
  2. SimpleDateFormat的实例化
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 = "2020/4/10 下午6:21";
    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);
    //解析:要求字符串必须是符合SimpleDateFormat识别的格式(通过构造器参数体现),
    Date date2 = sdf1.parse("2020-04-10 06:29:21");
    System.out.println(date2);
}

Calendar

Calendar是一个抽象类

  1. 实例化
    方式一:创建其子类(GregorianCalendar)的对象
    方式二:调用其静态方法getInstance()

  2. 常用方法
    get()
    set()
    add()
    gettime()
    settime()

获取月份时:一月是1,二月是2···
获取星期时:周日是1,周一是2···

扫描二维码关注公众号,回复: 10685719 查看本文章
public void testCalendar() {
	//调用其静态方法getInstance()
    Calendar calendar = Calendar.getInstance();

    //get()
    int days = calendar.get(Calendar.DAY_OF_MONTH);
    System.out.println(days);
    System.out.println(calendar.get(Calendar.DAY_OF_YEAR));

    //set()
    //calendar可变性
    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);
}

JDK 8中新日期时间API

LocalTime/LocalDateTime/LocalDate等

Calendar类的缺点:

  1. 可变性:像日期和时间这样的类应该是不可变的
  2. 偏移性:Date中的年份是从1900开始的,而月份都从0开始
  3. 格式化:格式化只对Date有用,Calendar则不行
  4. 它们也不是线程安全的;不能处理闰秒等

Java 8 吸收了 Joda-Time 的精华,以一个新的开始为 Java 创建优秀的 API。新的 java.time 中包含了所有关于本地日期(LocalDate)、本地时间(LocalTime)、本地日期时间(LocalDateTime)、时区(ZonedDateTime)和持续时间(Duration)的类。历史悠久的 Date 类新增了 toInstant() 方法,用于把 Date 转换成新的表示形式。这些新增的本地化时间日期 API 大大简化了日期时间和本地化的管理

now() / * now(ZoneId zone) 静态方法,根据当前时间创建对象/指定时区的对象
of() 静态方法,根据指定日期/时间创建对象
getDayOfMonth()/getDayOfYear() 获得月份天数(1-31) /获得年份天数(1-366)
getDayOfWeek() 获得星期几(返回一个 DayOfWeek 枚举值)
getMonth() 获得月份, 返回一个 Month 枚举值
getMonthValue() / getYear() 获得月份(1-12) /获得年份
getHour()/getMinute()/getSecond() 获得当前对象对应的小时、分钟、秒
withDayOfMonth()/withDayOfYear()/withMonth()/withYear() 将月份天数、年份天数、月份、年份修改为指定的值并返回新的对象
plusDays(), plusWeeks(), plusMonths(), plusYears(),plusHours() 向当前对象添加几天、几周、几个月、几年、几小时
minusMonths() / minusWeeks()/minusDays()/minusYears()/minusHours() 从当前对象减去几月、几周、几天、几年、几小时

//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);//2020-04-10
System.out.println(localDate1);//2020-04-22

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:时间线上的一个瞬时点。 这可能被用来记录应用程序中的事件时间戳
  • 在UNIX中,这个数从1970年开始,以秒为的单位;同样的,在Java中,也是从1970年开始,但以毫秒为单位
  • java.time包通过值类型Instant提供机器视图,不提供处理人类意义上的时间单位

now() 静态方法,返回默认UTC时区的Instant类的对象
ofEpochMilli(long epochMilli) 静态方法,返回在1970-01-01 00:00:00基础上加上指定毫秒数之后的Instant类的对象
atOffset(ZoneOffset offset) 结合即时的偏移来创建一个 OffsetDateTime
toEpochMilli() 返回1970-01-01 00:00:00到当前时间的毫秒数,即为时间戳

//now():获取本初子午线对应的标准时间
Instant instant = Instant.now();
System.out.println(instant);//2020-04-10T11:41:57.498666600Z

//添加时间的偏移量
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime);//2020-04-10T19:41:57.498666600+08:00

//toEpochMilli():获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数  --> Date类的getTime()
long milli = instant.toEpochMilli();
System.out.println(milli);

//ofEpochMilli():通过给定的毫秒数,获取Instant实例  -->Date(long millis)
Instant instant1 = Instant.ofEpochMilli(1586518917498L);
System.out.println(instant1);

DateTimeFormatter

DateTimeFormatter:格式化或解析日期、时间
类似于SimpleDateFormat

ofPattern(String pattern) 静态方法 , 返 回 一 个 指 定 字 符 串 格 式 的DateTimeFormatter
format(TemporalAccessor t) 格式化一个日期、时间,返回字符串
parse(CharSequence text) 将指定格式的字符序列解析为一个日期、时间

//方式一:预定义的标准格式。如: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);//2020-04-10T19:46:34.049618

//解析:字符串 -->日期
TemporalAccessor parse = formatter.parse("2020-04-10T19:46:34.049618");
System.out.println(parse);

//方式二:
//本地化相关的格式:ofLocalizedDateTime()
//FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime
DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
//格式化
String str2 = formatter1.format(localDateTime);
System.out.println(str2);


//本地化相关的格式:ofLocalizedDate()
//FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate
DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
//格式化
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);//2020-04-10 08:02:27

//解析
TemporalAccessor accessor = formatter3.parse("2020-04-10 08:02:27");
System.out.println(accessor);

Java比较器

一、说明:Java中的对象,正常情况下,只能进行比较:== 或 != ;不能使用 > 或 < ,但是在开发场景中,我们需要对多个对象进行排序,言外之意,就需要比较对象的大小 —> 使用两个接口中的任何一个:Comparable 或 Comparator

二、Comparable接口与Comparator的使用的对比:
Comparable接口的方式一旦一定,保证Comparable接口实现类的对象在任何位置都可以比较大小。 Comparator接口属于临时性的比较。

Comparable接口

Comparable接口的使用举例:自然排序

  1. String、包装类等实现了Comparable接口,重写了compareTo(obj)方法,给出了比较两个对象大小的方式
  2. String、包装类重写compareTo()方法以后,进行了从小到大的排列
  3. 重写compareTo(obj)的规则:
    如果当前对象this大于形参对象obj,则返回正整数;
    如果当前对象this小于形参对象obj,则返回负整数;
    如果当前对象this等于形参对象obj,则返回零
  4. 对于自定义类来说,如果需要排序,我们可以让自定义类实现Comparable接口,重写compareTo(obj)方法
    在compareTo(obj)方法中指明如何排序
String[] arr = new String[]{"AA", "CC", "KK", "MM", "GG", "JJ", "DD"};

Arrays.sort(arr);

System.out.println(Arrays.toString(arr));//[AA, CC, DD, GG, JJ, KK, MM]
//Goods类
public class Goods implements Comparable {

    private String name;
    private double price;

    public Goods() {
        
    }

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

    public Goods(String name, double price) {
        this.name = name;
        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 -this.name.compareTo(goods.name);
            }
            //方式二:包装类
            //return Double.compare(this.price,goods.price);
        }
        throw new RuntimeException("传入的数据类型不一致!");
    }
}
Goods[] arr = new Goods[5];
arr[0] = new Goods("lenMouse", 34);
arr[1] = new Goods("dellMouse", 43);
arr[2] = new Goods("xiiMouse", 12);
arr[3] = new Goods("huiMouse", 65);
arr[4] = new Goods("microsoftMouse", 43);

Arrays.sort(arr);

System.out.println(Arrays.toString(arr));

Comparator接口

Comparator接口的使用:定制排序

  1. 背景:
    当元素的类型没有实现java.lang.Comparable接口而又不方便修改代码,或者实现了java.lang.Comparable接口的排序规则不适合当前的操作,那么可以考虑使用 Comparator 的对象来排序
  2. 重写compare(Object o1,Object o2)方法,比较o1和o2的大小:
    如果方法返回正整数,则表示o1大于o2;
    如果返回0,表示相等;
    返回负整数,表示o1小于o2
String[] arr = new String[]{"AA", "CC", "KK", "MM", "GG", "JJ", "DD"};
Arrays.sort(arr, new Comparator() {

    //按照字符串从大到小的顺序排列
    @Override
    public 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));
Goods[] arr = new Goods[6];
arr[0] = new Goods("lenovoMouse", 34);
arr[1] = new Goods("dellMouse", 43);
arr[2] = new Goods("xiaomiMouse", 12);
arr[3] = new Goods("huaweiMouse", 65);
arr[4] = new Goods("huaweiMouse", 224);
arr[5] = new Goods("microsoftMouse", 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));

System类

  • System类代表系统,系统级的很多属性和控制方法都放置在该类的内部。该类位于java.lang包

  • 由于该类的构造器是private的,所以无法创建该类的对象,也就是无法实例化该类。其内部的成员变量和成员方法都是static的,所以也可以很方便的进行调用

  • 成员变量

    • System类内部包含in、out和err三个成员变量,分别代表标准输入流(键盘输入),标准输出流(显示器)和标准错误输出流(显示器)
  • 成员方法

    1. native long currentTimeMillis():该方法的作用是返回当前的计算机时间,时间的表达格式为当前计算机时间和GMT时间(格林威治时间)1970年1月1号0时0分0秒所差的毫秒数
    2. void exit(int status):该方法的作用是退出程序。其中status的值为0代表正常退出,非零代表异常退出。使用该方法可以在图形界面编程中实现程序的退出功能等
    3. void gc():该方法的作用是请求系统进行垃圾回收。至于系统是否立刻回收,则取决于系统中垃圾回收算法的实现以及系统执行时的情况
    4. String getProperty(String key):该方法的作用是获得系统中属性名为key的属性对应的值。系统中常见的属性名以及属性的作用如下表所示
属性名 属性说明
java.version java运行时环境版本
java.home java安装目录
os.name 操作系统的名称
os.version 操作系统的版本
user.name 用户的账户名称
user.home 用户的主目录
user.dir 用户当前的工作目录
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类

java.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

  • java.math包的BigInteger可以表示不可变的任意精度的整数。BigInteger 提供所有 Java 的基本整数操作符的对应物,并提供 java.lang.Math 的所有相关方法。另外,BigInteger 还提供以下运算:模算术、GCD 计算、质数测试、素数生成、位操作以及一些其他操作

  • 构造器
    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


  • 一般的Float类和Double类可以用来做科学计算或工程计算,但在商业计算中,要求数字精度比较高,故用到java.math.BigDecimal类

  • 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, int scale, int roundingMode)

发布了33 篇原创文章 · 获赞 48 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42224119/article/details/105422640
今日推荐