目录
- 数值计算:Math,StrictMath,BigInteger,BigDecimal
- 字符串处理:String,StringBuilder,StringBuffer
- 日期处理:LocalDateTime,DateTimeFormatter,Instant
- 数组和枚举: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 对象。示例如下:
(2)使用除法时尽量指定"要精确的小数位数"和"舍入模式"这两个参数,避免运行时出错(余数不为零的情况)。示例如下: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...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 的辅助类,用于提供操作数组的各种方法,如排序,二分查找和将数组转换为列表等方法。