第六章. Java常用类
1. Java类库文档
Java类库文档:Java官方API文档
- https://docs.oracle.com/javase/8/docs/api/
Java类库:
- 包名以 java 开始的包是 Java 核心包 (Java Core Package) ;
- 包名以 javax 开始的包是 Java 扩展包 (Java Extension Package)
常见Java类:
2. 数字相关类
2.1 Java 数字类
大整数类BigInteger
- 支持无限大的整数运算
大浮点数BigDecimal - 支持无限大的小数运算
- 注意精度和截断
2.2 随机数类
Random 随机数
- nextInt() 返回一个随机int
- nextInt(int a) 返回一个[0,a)之间的随机int
- nextDouble()返回一个[0.0,1.0]之间double
- ints 方法批量返回随机数数组
Math.random() :返回一个[0.0,1.0]之间double
2.3 数字工具类
java.lang.Math
- 绝对值函数abs
- 对数函数log
- 比较函数max、min
- 幂函数pow
- 四舍五入函数round等
- 向下取整floor
- 向上取整ceil
3. 字符串相关类
3.1 String
String
- Java中使用频率最高的类
- 是一个不可变对象,加减操作性能较差
- 以下方法需要牢记:charAt, concat, contains, endsWith,equals,
equalsIgnoreCase, hashCode, indexOf, length, matches, replace,
replaceAll, split, startsWith, subString, trim, valueOf
public class StringTest {
public static void main(String[] args) {
String a = "123;456;789;123 ";
System.out.println(a.charAt(0)); // 返回第0个元素
System.out.println(a.indexOf(";")); // 返回第一个;的位置
System.out.println(a.concat(";000")); // 连接一个新字符串并返回,a不变
System.out.println(a.contains("000")); // 判断a是否包含000
System.out.println(a.endsWith("000")); // 判断a是否以000结尾
System.out.println(a.equals("000")); // 判断是否等于000
System.out.println(a.equalsIgnoreCase("000"));// 判断在忽略大小写情况下是否等于000
System.out.println(a.length()); // 返回a长度
System.out.println(a.trim()); // 返回a去除前后空格后的字符串,a不变
String[] b = a.split(";"); // 将a字符串按照;分割成数组
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
System.out.println("===================");
System.out.println(a.substring(2, 5)); // 截取a的第2个到第5个字符 a不变
System.out.println(a.replace("1", "a"));
System.out.println(a.replaceAll("1", "a")); // replaceAll第一个参数是正则表达式
System.out.println("===================");
String s1 = "12345?6789";
String s2 = s1.replace("?", "a");
String s3 = s1.replaceAll("[?]", "a");
// 这里的[?] 才表示字符问号,这样才能正常替换。不然在正则中会有特殊的意义就会报异常
System.out.println(s2);
System.out.println(s3);
System.out.println(s1.replaceAll("[\\d]", "a")); //将s1内所有数字替换为a并输出,s1的值未改变。
}
}
3.1 可变字符串(StringBuffer、StringBuilder)
- StringBuffer(字符串加减,同步,性能好)
- StringBuilder(字符串加减,不同步,性能更好)
StringBuffer/StringBuilder: 方法一样,区别在同步
- append/insert/delete/replace/substring
- length 字符串实际大小,capacity字符串占用空间大小
- trimToSize(): 去除空隙,将字符串存储压缩到实际大小
- 如有大量append,事先预估大小,再调用相应构造函数
public class StringBufferReferenceTest {
public static void main(String[] args) {
StringBuffer sb1 = new StringBuffer("123");
StringBuffer sb2 = sb1;
sb1.append("12345678901234567890123456789012345678901234567890");
System.out.println(sb2); //sb1 和 sb2还是指向同一个内存的
}
}
4. 时间相关类
4.1 Java 8 推出新的时间API
- java.time包
–旧的设计不好 (重名的类、线程不安全等)
–新版本优点
• 不变性,在多线程环境下
• 遵循设计模式,设计得更好,可扩展性强
4.2 Java 8 时间包概述
- java.time包:新的Java日期/时间API的基础包
- java.time.chrono包:为非ISO的日历系统定义了一些泛
化的API, - java.time.format包:格式化和解析日期时间对象的类
- java.time.temporal包:包含一些时态对象,可以用其找
出关于日期/时间对象的某个特定日期或时间 - java.time.zone包:包含支持不同时区以及相关规则的
4.3 Java 8 java.time包主要类
- LocalDate:日期类
- LocalTime:时间类(时分秒-纳秒)
- LocalDateTime: LocalDate + LocalTime
- Instant: 时间戳
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
public class LocalDateExample {
public static void main(String[] args) {
//当前时间
LocalDate today = LocalDate.now();
System.out.println("Current Date="+today);
//根据指定时间创建LocalDate
LocalDate firstDay_2014 = LocalDate.of(2014, Month.JANUARY, 1);
System.out.println("Specific Date="+firstDay_2014);
//给定错误时间参数,将报异常java.time.DateTimeException
//LocalDate feb29_2014 = LocalDate.of(2014, Month.FEBRUARY, 29);
//可以更改时区
LocalDate todayBeijing = LocalDate.now(ZoneId.of("Asia/Shanghai"));
System.out.println("Current Date in Shanghai="+todayBeijing);
//从纪元日01/01/1970开始365天
LocalDate dateFromBase = LocalDate.ofEpochDay(365);
System.out.println("365th day from base date= "+dateFromBase);
//2014年的第100天
LocalDate hundredDay2014 = LocalDate.ofYearDay(2014, 100);
System.out.println("100th day of 2014="+hundredDay2014);
}
}
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZoneOffset;
public class LocalDateTimeExample {
public static void main(String[] args) {
//当前日期 时分秒
LocalDateTime today = LocalDateTime.now();
System.out.println("Current DateTime="+today);
//根据日期, 时分秒来创建对象
today = LocalDateTime.of(LocalDate.now(), LocalTime.now());
System.out.println("Current DateTime="+today);
//指定具体时间来创建对象
LocalDateTime specificDate = LocalDateTime.of(2014, Month.JANUARY, 1, 10, 10, 30);
System.out.println("Specific Date="+specificDate);
//如时间不对,将报异常DateTimeException
//LocalDateTime feb29_2014 = LocalDateTime.of(2014, Month.FEBRUARY, 28, 25,1,1);
//上海时区
LocalDateTime todayShanghai = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
System.out.println("Current Date in Shanghai="+todayShanghai);
//从01/01/1970 10000秒
LocalDateTime dateFromBase = LocalDateTime.ofEpochSecond(10000, 0, ZoneOffset.UTC);
System.out.println("10000th second time from 01/01/1970= "+dateFromBase);
}
}
5. 格式化类
java.text包java.text.Format的子类
- NumberFormat:数字格式化,抽象类
• DecimalFormat - MessageFormat:字符串格式化
- DateFormat:日期/时间格式化,抽象类
• SimpleDateFormat
5.1 NumberFormat:数字格式化,抽象类
- DecimalFormat 工厂模式
例如:将1234567格式化输出为1,234,567
import java.text.DecimalFormat;
public class DecimalFormatTest {
public static void main(String[] args) {
DecimalFormat df1 = new DecimalFormat("0.0");
DecimalFormat df2 = new DecimalFormat("#.#");
DecimalFormat df3 = new DecimalFormat("000.000");
DecimalFormat df4 = new DecimalFormat("###.###");
System.out.println(df1.format(12.34)); //12.3
System.out.println(df2.format(12.34)); //12.3
System.out.println(df3.format(12.34)); //012.340
System.out.println(df4.format(12.34)); //12.34
DecimalFormat df5 = new java.text.DecimalFormat("0.00");// 保留2位小数
double d1 = 123456789.123456;
double d2 = 987654321.987654321;
System.out.println("format1_d1=" + df5.format(d1));// 输出format1_d1=123456789.12
System.out.println("format1_d2=" + df5.format(d2));// format1_d2=987654321.99
// 四舍五入
DecimalFormat df6 = new DecimalFormat("#,##0.00");
System.out.println("format2_d1=" + df6.format(d1));// 输出:format2_d1=123,456,789.12
System.out.println("format2_d2=" + df6.format(d2));// 输出:format2_d2=987,654,321.99
// 四舍五入
}
}
5.2 MessageFormat:字符串格式化
- 支持多个参数-值对位复制文本
- 支持变量的自定义格式
例如将”Hello {1}”根据变量值格式化为Hello World
import java.text.MessageFormat;
public class MessageFormatTest {
public static void main(String[] args) {
String message = "{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}{13}{14}{15}{16}";
Object[] array = new Object[]{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q"};
String value = MessageFormat.format(message, array); //ABCDEFGHIJKLMNOPQ
System.out.println(value);
message = "oh, {0,number,#.##} is a good number";
array = new Object[]{new Double(3.1415)};
value = MessageFormat.format(message, array); // oh, 3.1415 is a good number
System.out.println(value);
}
}
5.3 DateFormat:时间格式化,抽象类
- SimpleDateFormat 工厂模式
- parse:将字符串格式化为时间对象
- format:将时间对象格式化为字符串
–如将当前时间转为化YYYY-MM-DD HH24:MI:SS输出
- java.time.format.DateFormatter:时间格式化
- JDK 8 发布,线程安全(vs SimpleDateFormat 线程不安全)
- ofPattern: 设定时间格式
- parse:将字符串格式化为时间对象
- format:将时间对象格式化为字符串
- 如将当前时间转为化YYYY-MM-DD HH24:MI:SS输出
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateTest {
public static void main(String[] args) {
String strDate = "2008-10-19 10:11:30.345" ;
// 准备第一个模板,从字符串中提取出日期数字
String pat1 = "yyyy-MM-dd HH:mm:ss.SSS" ;
// 准备第二个模板,将提取后的日期数字变为指定的格式
String pat2 = "yyyy年MM月dd日 HH时mm分ss秒SSS毫秒" ;
SimpleDateFormat sdf1 = new SimpleDateFormat(pat1) ; // 实例化模板对象
SimpleDateFormat sdf2 = new SimpleDateFormat(pat2) ; // 实例化模板对象
Date d = null ;
try{
d = sdf1.parse(strDate) ; // 将给定的字符串中的日期提取出来
}catch(Exception e){ // 如果提供的字符串格式有错误,则进行异常处理
e.printStackTrace() ; // 打印异常信息
}
System.out.println(sdf2.format(d)) ; // 将日期变为新的格式
}
}
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateFormatterTest {
public static void main(String[] args) {
//将字符串转化为时间
String dateStr= "2016年10月25日";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
LocalDate date= LocalDate.parse(dateStr, formatter);
System.out.println(date.getYear() + "-" + date.getMonthValue() + "-" + date.getDayOfMonth());
// 2016-10-25
System.out.println("==========================");
//将日期转换为字符串输出
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy年MM月dd日 hh:mm:ss");
String nowStr = now.format(format);
System.out.println(nowStr);
}
}