Java笔记:基本类库汇总

目录

  1. 数值计算:Math,StrictMath,BigInteger,BigDecimal
  2. 字符串处理:String,StringBuilder,StringBuffer
  3. 日期处理:LocalDateTime,DateTimeFormatter,Instant
  4. 数组和枚举:Array,Enum,Arrays

1. 数值计算:Math,StrictMath,BigInteger,BigDecimal

1.1 类库简介

  • Math 和 StrictMath 包含了几乎完全相同的基本数值运算方法(两者的主要区别在于底层实现不同),如指数、对数、平方根和三角函数等。如果效率更重要,则使用 Math 类;如果可移植性更重要,则使用 StrictMath。
  • BigInteger 和 BigDecimal 分别提供任意精度整数运算和任意精度十进制运算的方法,后者通常用于货币计算。

1.2 备注

  • 使用 BigDecimal 的两条注意事项:
    (1)使用构造方法 BigDecimal(String) 或静态方法 BigDecimal.valueOf() 来创建 BigDecimal 对象。示例如下:
    BigDecimal a = new BigDecimal("0.1");  // 推荐
    BigDecimal b = BigDecimal.valueOf(0.1);  // 推荐
    BigDecimal c = new BigDecimal(0.1);  // 不推荐
    System.out.println(a);  // 打印 0.1
    System.out.println(b);  // 打印 0.1
    System.out.println(c);  // 打印 0.1000000000000000055511...
    
    (2)使用除法时尽量指定"要精确的小数位数"和"舍入模式"这两个参数,避免运行时出错(余数不为零的情况)。示例如下:
    BigDecimal a = new BigDecimal("1");
    BigDecimal b = new BigDecimal("3");
    BigDecimal c = a.divide(b);  // 运行时出错,余数不为零
    BigDecimal d = a.divide(b, 5, BigDecimal.ROUND_HALF_UP);  // 0.33333
    

2. 字符串处理:String,StringBuilder,StringBuffer

2.1 类库简介

  • String 是不可变的字符序列。StringBuilder 和 StringBuffer 都是可变的字符序列,两者的区别在于 StringBuffer 是线程安全的,而 StringBuilder 不是线程安全的(因而效率要高一些)。这三个类包含的方法有部分交集,总的来说,String 包含的方法更多,而后两者主要提供了 append,insert 和 delete 这三个额外的方法。

2.2 备注

  • String a = "hello" 和 String a = new String("hello") 的区别:前者将字符串存储在常量池中,效率高,但内存会被长时间占用;后者将字符串存储在堆内存中,效率低,但内存可被垃圾回收器回收。

3. 日期处理:LocalDateTime,DateTimeFormatter,Instant

3.1 类库简介

  • LocalDateTime 用于获取日期和时间对象。用法示例:
    LocalDateTime now = LocalDateTime.now();
    System.out.println("年=" + now.getYear());
    System.out.println("月=" + now.getMonth());  // 枚举类型,JANUARY~DECEMBER
    System.out.println("月=" + now.getMonthValue());  // 数值类型,1~12
    System.out.println("日=" + now.getDayOfMonth());
    System.out.println("时=" + now.getHour());
    System.out.println("分=" + now.getMinute());
    System.out.println("秒=" + now.getSecond());
    
  • DateTimeFormatter 用于格式化和解析日期和时间对象。用法示例:
    LocalDateTime now = LocalDateTime.now();
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
    System.out.println("格式化的日期=" + dtf.format(now));
    
  • Instant 用于表示时间线上的某个瞬间点(时间戳)。用法示例:
    Instant now = Instant.now();
    Date date = Date.from(now);  // Instant to Date
    Instant instant = date.toInstant();  // Date to Instant
    

3.2 备注

  • LocalDateTime,DateTimeFormatter,Instant 由 JDK8 引入,可用于替代之前的 Calendar,DateTimeFormatter,Date。

4. 数组和枚举:Array,Enum,Arrays

4.1 类库简介

  • Array 可简单理解为存储一组变量的集合(容量固定)。
  • Enum 可简单理解为存储一组常量的集合(容量固定)。
  • Arrays 可理解为 Array 的辅助类,用于提供操作数组的各种方法,如排序,二分查找和将数组转换为列表等方法。
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容