一、常用API
1. Object类
1.1 Object类作用:
- Object类是java中祖宗类,要么默认继承,要么间接继承;
- Object类的方法一切子类都可直接用
1.2 Object类的常用方法
1.2.1 toString()
| 方法名 | 说明 | toString()存在意义: |
|---|---|---|
public String toString() | 默认返回当前对象在堆内存中的地址信息: 类的全限名@内存地址 | 父类toString()方法存在意义为了被子类重写 ,方便返回对象内容信息,而不是地址信息 |
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
public static void main(String[] args) {
Student student = new Student("zyf", "nan", 18);
System.out.println(student);//默认使用toString
System.out.println(student.toString());
}
1.2.2 equals()
| 方法名 | 说明 | 意义 |
|---|---|---|
public Boolean equals(Object o) | 默认比较两个对象地址是否相同,相同返回true | 子类重写,定制规则 |
/** 官方:
* 同一对象 返回true
* 如果o为null或者类型不同 返回false
* @param o
* @return
*/
@Override
public boolean equals(Object o) {
//1.同一对象 返回true
if (this == o) return true;
//2.如果o为null或者类型不同 返回false
if (o == null || getClass() != o.getClass()) return false;
//3.强转后比较值
Student student = (Student) o;
return age == student.age &&
Objects.equals(name, student.name) &&
Objects.equals(sex, student.sex);
}
==================自制======================
@Override
public boolean equals(Object obj) {
if (obj instanceof Student){
//强转比较
Student s2 = (Student) obj;
//字符串的equals是重写过的,比较值
return this.name.equals(s2.name)
&& this.sex.equals(s2.sex)
&& this.age==s2.age ;
}else {
//不是学生类,不比较
return false;
}
}
2. Objects类
2.1 Objects类概述
| 方法名 | 说明 |
|---|---|
| public static boolean equals(Object a,Object b) | 比较两个对象,底层会先进行非空判断,避免空指针异常,再equals比较 |
- Objects类和Object是继承关系,JDK7后出现
- 官方进行字符串比较时,没有用Object的equals,而是用Objects类的equals方法来比较两个对象;
- Objects类的方法比较结果一样,但更安全;
- 安全,进行了非空校验;
- Objects类的方法比较结果一样,但更安全;
String a = null;
String b = new String("a");
//报错
System.out.println(a.equals(b));
System.out.println(Objects.equals(a,b));
===============源码==================================
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
2.2 isNull
| 方法名 | 说明 |
|---|---|
| public static boolean isNull(Object obj) | 判断变量是否为Null,为null返回true |
3. StringBuilder
3.1概述
-
StringBuilder是一个可变字符串类,可以看为一个对象容器
-
作用:提高字符操作效率,如:拼接,修改
3.1.1 String类拼接字符串原理
3.1.2 StringBuilder提高效率原理
3.1.3 总结
- String拼接需要通过StringBuilder对象;
- 每次拼接创建一个StringBuilder对象;创建一个String对象;
- StringBuilder拼接只需一个StringBuilder对象
/**
* StringBuilder常用API
*/
public class StringBuilderDemo1 {
public static void main(String[] args) {
StringBuilder a = new StringBuilder();
a.append('a');
a.append(9.9);
System.out.println(a);
StringBuilder b = new StringBuilder();
//支持链式编程,
b.append('a').append("bcd").append(9).append(2.5);
System.out.println(b);//abcd92.5
//reverse()先翻转已有的
b.reverse().append(110);
System.out.println(b);//5.29dcba110
b.length();//取长度
/**
* StringBuilder:只是拼接字符串的手段
* 最终目的恢复成String
*/
String rs = b.toString();
}
/**
* 拼接输出数组
*/
public class StringBuilderDemo2 {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6};
System.out.println(toString(arr));
int[] arr2 = {};
System.out.println(toString(arr2));
}
public static String toString(int[] arr) {
if (arr != null){
StringBuilder data = new StringBuilder("[");
for (int i = 0; i < arr.length; i++) {
data.append(arr[i]).append(i == arr.length-1 ?"": ",");
}
//"]"写在上面,arr=0,出问题
data.append("]");
String rs = data.toString();
return rs;
}else {
return null;
}
}
}
4.Math类
- 执行基本数字运算 的方法,没有提供公开的构造器,不可new;
- 工具类直接调用方法;
/**
* Math类
*/
public class MathDemo {
public static void main(String[] args) {
//1.取绝对值
System.out.println(Math.abs(10.6));
System.out.println(Math.abs(-10.6));
//2.向上取整
System.out.println(Math.ceil(4.0001));//5.0
//3.向下取整
System.out.println(Math.floor(4.999));//4.0
//4.求指数次方
System.out.println(Math.pow(2,3));//2^3=8.0
//5.四舍五入
System.out.println(Math.round(4.4999));//4
System.out.println(Math.round(4.5001));//5
System.out.println(Math.random());//【0.0,1.0)之间 包前不包后 0.9855462
//3-9间随机数 [0-7)+3 取整
int data = (int) (Math.random()*7 +3);
}
}
5.System类
系统类,直接调用;
/**
* System类
*/
public class SystemDemo {
public static void main(String[] args) {
System.out.println("start!!!");
//JVM终止
// System.exit(0);
//计算机时间起源为1970-1-1 00:00:00
long time = System.currentTimeMillis();
//计算时间差
long startTime = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
System.out.println(i);
}
long endTime = System.currentTimeMillis();
System.out.println("循环运行时间:"+(startTime-endTime)/1000.0+"s");
/**
* 数组拷贝
* arraycopy(Object src(被拷贝数组), int srcPos(拷贝开始索引),
* Object dest(目标数组), int destPos(数组开始粘贴位置),
* int length(拷贝元素个数));
*/
int[] arr1 = {10,20,30,40,50,60};
int[] arr2 = new int[6];//[0,0,0,....]-->[0,0,40,50,60,0]
System.arraycopy(arr1,3,arr2,2,3);
System.out.println(Arrays.toString(arr2));
}
}
6.BigDecimal类
-
用于解决浮点型运算精度失真问题;
-
创建BigDecimal对象封装浮点型数据,进行运算;
/**
* BigDecimal类
* 创建该对象一定要调用BigDecimal.valueOf(a);
* 不能之间new
*/
public class BigDecimalDemo {
public static void main(String[] args) {
//浮点型之间运算会数据失真
System.out.println(0.09 + 0.01);//0.09999999999999999
System.out.println(1.0 - 0.32);//0.6799999999999999
System.out.println(1.015 * 100);//101.49999999999999
System.out.println(1.301 / 100);//0.013009999999999999
System.out.println("====================");
double a = 0.1;
double b = 0.2;
double c = a+b;
System.out.println(c);//0.30000000000000004
System.out.println("=========================");
BigDecimal a1 = BigDecimal.valueOf(a);
BigDecimal b1 = BigDecimal.valueOf(b);
BigDecimal c1 = a1.add(b1);
System.out.println(c1);// + 0.3
BigDecimal c2 = a1.subtract(b1);
System.out.println(c2);//- -0.1
BigDecimal c3 = a1.multiply(b1);
System.out.println(c3);//* 0.02
BigDecimal c4 = a1.divide(b1);
System.out.println(c4);// / 0.5
//目的:生成double
double rs = c1.doubleValue();
//注意:BigDecimal一定要精确运算有结果,不然报错
BigDecimal a11 = BigDecimal.valueOf(10.0);
BigDecimal b11 = BigDecimal.valueOf(3.0);
//3.3333....除不开;报错;
//处理,保留两位小数;BigDecimal.ROUND_HALF_UP四舍五入
BigDecimal c11 = a11.divide(b11,2,BigDecimal.ROUND_HALF_UP);
}
}
二、日期与时间类
1.Date类
Date类对象代表系统当前时间;
/**
* Data类常用API
*/
public class DateDemo1 {
public static void main(String[] args) {
Date date = new Date();
//Fri Jul 22 21:06:12 CST 2022
System.out.println(date);
//效果一致,获取java起始到现在的时间毫秒值
long time = date.getTime();
System.out.println(time);
long time1 = System.currentTimeMillis();
System.out.println("================");
//1.当前时间
Date d1 = new Date();
System.out.println(d1);
//2.当前时间后一小时121s后
long time2 = d1.getTime();
time2+=(60 * 60 + 121) * 1000;
//3.时间毫秒值转为日期对象
Date d2 = new Date(time2);
System.out.println(d2);
/* Date d2 = new Date();
d2.setTime(time2);*/
}
}
2.SimpleDateFormat类
- 可以设置Date对象或时间毫秒的时间展示形式;
- 可以把字符串的时间形式解析成日期对象;
/**
* SimpleDateFormat类常用API
*/
public class SimpleDateFormatDemo {
public static void main(String[] args) {
Date d = new Date();
System.out.println(d);
/**
* yyyy 2022
* EEE 周几
* a 上午下午
*/
//1.格式化日期对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE a");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss EEE a");
String rs = sdf.format(d);
//2022-07-22 21:27:13 星期五 下午
System.out.println(rs);
String rs2 = sdf2.format(d);
//2022年07月22日 21:27:13 星期五 下午
System.out.println(rs2);
//2.格式化时间毫秒值
long l = System.currentTimeMillis();
String rs3 = sdf.format(l);
System.out.println(rs3);
}
}
/**
* SimpleDateFormat解析字符串:
* 拿到一个时间字符串,求两天14小时49分06秒后是什么时间
*/
public class SimpleDateFormatDemo2 {
public static void main(String[] args) throws ParseException {
//1.拿到时间
String dateStr = "2021年08月06日 11:11:11";
//2.字符串解析成日期对象,时间形式完全一致
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date d = sdf.parse(dateStr);
//3.往后走后的时间,计算时采用L,int型计算,数据量可能越界
long time = d.getTime() + (2L*24*60*60 + 14*60*60 + 49*60 + 6 ) * 1000;
//4.格式化时间毫秒值
String rs = sdf.format(time);
System.out.println(rs);
}
}
/**
* SimpleDateFormat解析字符串:
* 秒杀活动
*/
public class SimpleDateFormatDemoTest {
public static void main(String[] args) throws ParseException {
String startTime = "2021-11-11 00:00:00";
String endTime = "2021-11-11 00:10:00";
String jiaTime = "2021-11-11 00:03:47";
String xpTime = "2021-11-11 00:10:11";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = sdf.parse(startTime);
Date endDate = sdf.parse(endTime);
Date jiaDate = sdf.parse(jiaTime);
Date xpDate = sdf.parse(xpTime);
if (jiaDate.after(startDate) && jiaDate.before(endDate)){
System.out.println("小贾成功秒杀");
}else {
System.out.println("小贾失败了");
}
if (xpDate.after(startDate) && xpDate.before(endDate)){
System.out.println("小皮成功秒杀");
}else {
System.out.println("小皮失败了");
}
}
}
2.1设置的大小Y和y有区别吗?
-
new SimpleDateFormat("YYYY-MM-dd");
-
y 是Year, Y 表示的是Week year
-
Week year 意思是当天所在的周属于的年份,一周从周日开始,周六结束,只要本周跨年,那么这周就算入下一年。
-
正确写法应该是
SimpleDateFormat dateFormat = new SimpleDateFormat("**yyyy**-MM-dd");
2.2 补充:sql语句设置时间格式
语法: DATE_FORMAT(date,format) 其中,date 参数是合法的日期。format 规定日期/时间的输出格式。
date_format(#{param.countTime}, '%Y-%m-%d')
SELECT username,date_format(create_time,'%Y-%m-%d') FROM community.user;
DATE_FORMAT(NOW(),'%b %d %Y %h:%i %p') --Dec 29 2008 11:45 PM
DATE_FORMAT(NOW(),'%m-%d-%Y') --12-29-2008
DATE_FORMAT(NOW(),'%d %b %y') --29 Dec 08
DATE_FORMAT(NOW(),'%d %b %Y %T:%f') --29 Dec 2008 16:25:46.635
 函数.png)
3.Calendar类
- 代表日历对象;
- 抽象类,不能之间创建对象;
- 注意:Calendar是可变日期对象,修改后对本身时间产生变化
/**
* Calendar类
*/
public class CalendarDemo {
public static void main(String[] args) {
//1.拿到系统此刻日历对象
Calendar cal = Calendar.getInstance();
//firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=6,WEEK_OF_YEAR=30,WEEK_OF_MONTH=4,DAY_OF_MONTH=22
// ,DAY_OF_YEAR=203,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=58,SECOND=25
// ,MILLISECOND=962,ZONE_OFFSET=28800000,DST_OFFSET=0]
System.out.println(cal);
//2.获取日历某一字段
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH)+1;
int days = cal.get(Calendar.DAY_OF_YEAR);
System.out.println(year+"年"+month+"月"+days);
//3.修改日历某个字段信息;
cal.set(Calendar.HOUR,12);
//4.为某个字段增加、减少指定时间
//64天59分后
cal.add(Calendar.DAY_OF_YEAR,64);
cal.add(Calendar.MINUTE,59);
//5.拿到此刻日期对象
Date d = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String rs = sdf.format(d);
System.out.println(rs);
//6.拿到时间毫秒值
long timeInMillis = cal.getTimeInMillis();
System.out.println(timeInMillis);
}
}
二、JDK8新增日期类
新API几乎全部是不变类型,不用担心被修改
| 类型 | |
|---|---|
| LocalDate | 只有日期 |
| LocalTime | 只有时间 |
| LocalDateTime | 日期和时间 |
| Instant | 时间戳 |
| DateTimeFormatter | 时间格式化和解析 |
| Duration | 计算时间间隔 |
| Period | 计算日期间隔 |
1.LocalDate、LocalTime、LocalDateTime,类实例是不可变对象
/**
* LocalDate
*/
public class Demo01LocalDate {
public static void main(String[] args) {
LocalDate nowDate = LocalDate.now();
System.out.println(nowDate);
int year = nowDate.getYear();
int monthValue = nowDate.getMonthValue();
int dayOfYear = nowDate.getDayOfYear();
int dayOfMonth = nowDate.getDayOfMonth();
DayOfWeek dayOfWeek = nowDate.getDayOfWeek();
int dayOfWeekValue = dayOfWeek.getValue();
//指定日期拿对象
LocalDate myDate = LocalDate.of(1999, 02, 23);
System.out.println(myDate);
LocalDate myDate2 = LocalDate.of(1999, Month.FEBRUARY, 23);
}
}
/**
* LocalTime
*/
public class Demo02LocalTime {
public static void main(String[] args) {
LocalTime nowTime = LocalTime.now();
int hour = nowTime.getHour();
int minute = nowTime.getMinute();
int second = nowTime.getSecond();
//纳秒
int nano = nowTime.getNano();
LocalTime.of(8,20);
LocalTime.of(8,20,58);
LocalTime.of(8,20,58,150);
LocalTime localTime = LocalTime.of(8, 20, 58, 150);
//年月日 时分秒 纳秒
LocalDateTime localDateTime = LocalDateTime.of(1991, 11, 11, 11, 11, 11, 111);
LocalDateTime localDateTime2 = LocalDateTime.of(1991, Month.NOVEMBER, 11, 11, 11, 11, 111);
}
}
/**
* LocalDateTime
*/
public class Demo03LocalDateTime {
public static void main(String[] args) {
LocalDateTime localDateTime = LocalDateTime.now();
int year = localDateTime.getYear();
/**
* 兼容前两者
*/
//兼容前两者,可以转换为前两者
LocalDate localDate = localDateTime.toLocalDate();
LocalTime localTime = localDateTime.toLocalTime();
}
}
/**
* UpdateTime
*/
public class Demo04UpdateTime {
public static void main(String[] args) {
//不可变对象,每次修改产生新对象
LocalTime localTime = LocalTime.now();
//一小时前;一分钟前,
localTime.minusHours(1);
localTime.minusMinutes(1);
localTime.minusSeconds(1);
localTime.minusNanos(1);
//一小时后,一分钟后
localTime.plusHours(1);
localTime.plusMinutes(1);
localTime.plusSeconds(1);
localTime.plusNanos(1);
LocalDate myDate = LocalDate.of(2018, 9, 3);
LocalDate nowDate = LocalDate.now();
//判断都是boolean型
nowDate.equals(myDate);
myDate.isBefore(nowDate);
myDate.isAfter(nowDate);
//判断生日
LocalDate myDate2 = LocalDate.of(1999, 2, 23);
LocalDate nowDate2 = LocalDate.now();
MonthDay my = MonthDay.of(myDate2.getMonthValue(), myDate2.getDayOfMonth());
MonthDay now = MonthDay.from(nowDate2);
// MonthDay now = MonthDay.of(nowDate2.getMonthValue(), nowDate2.getDayOfMonth());
if (my.equals(now)) {
System.out.println("生日快乐!");
}
}
}
2.Instant 时间戳
Instant类由一个静态工厂方法now()返回当前时间戳;
与Date类似,可以互相转换;
/**
* Instant时间戳
*/
public class Demo05Instant {
public static void main(String[] args) {
//世界时间 时间戳
Instant instant = Instant.now();
//2022-07-22T15:24:11.584Z
System.out.println(instant);
//转为系统默认时间,
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
//2022-07-22T23:24:11.584+08:00[Asia/Shanghai]
System.out.println(zonedDateTime);
//基本的增删
//Instant and Date 互相转换
Date date= Date.from(instant);
//Fri Jul 22 23:24:11 CST 2022
System.out.println(date);
Instant instant1 = date.toInstant();
//2022-07-22T15:24:11.584Z
System.out.println(instant1);
}
}
3.DateTimeFormatter:时间格式化和解析
- 全新的日期与时间格式器;
- 正反都能调用format方法;
/**
* DateTimeFormat
*/
public class Demo06DateTimeFormat {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
//解析,格式化器
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss EEE a");
//正向格式化
String now1 = dtf.format(now);
//2022-07-22 23:35:21 星期五 下午
System.out.println(now1);
//逆向格式化
String now2 = now.format(dtf);
//2022-07-22 23:35:21 星期五 下午
System.out.println(now2);
//解析字符串时间
DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateStr = "2022-07-22 23:34:55";
LocalDateTime ldt1 = LocalDateTime.parse(dateStr, dtf1);
//2022-07-22T23:34:55
System.out.println(ldt1);
}
}
4.Duration:计算时间间隔 Period:计算日期间隔
/**
* Period
*/
public class Demo07Period {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
//出生日期
LocalDate birthDate = LocalDate.of(1999, 02, 23);
//比较,计算现在年龄(today-birthDate)
Period between = Period.between(birthDate, today);
//现在年龄:23岁4个月29天
System.out.println("现在年龄:"+between.getYears()+"岁"+between.getMonths()+"个月"+between.getDays()+"天");
}
}
/**
* Duration
*/
public class Demo08Duration {
public static void main(String[] args) {
LocalDateTime today = LocalDateTime.now();
LocalDateTime birthDate = LocalDateTime.of(1999, 2, 23, 10, 48, 06, 06);
//新日期在后
Duration duration = Duration.between(birthDate,today);
//两个时间差的精确值,每个都单独使用
//差天数:最大单位即是天
long l = duration.toDays();//8800
System.out.println(l);
long ll = duration.toHours();//211218
System.out.println(ll);
duration.toMinutes();
duration.toMillis();//毫秒
duration.toNanos();
}
}
5.ChronoUnit类
用于在单个时间单位内测量一段时间,可以用于比较所有时间;
/**
* ChronoUnit
*/
public class Demo09ChronoUnit {
public static void main(String[] args) {
LocalDateTime today = LocalDateTime.now();
LocalDateTime birthDate = LocalDateTime.of(1999, 2, 23, 10, 48, 06, 06);
ChronoUnit.YEARS.between(birthDate,today);
ChronoUnit.MONTHS.between(birthDate,today);
ChronoUnit.WEEKS.between(birthDate,today);
ChronoUnit.DAYS.between(birthDate,today);
ChronoUnit.HOURS.between(birthDate,today);
ChronoUnit.MINUTES.between(birthDate,today);
ChronoUnit.SECONDS.between(birthDate,today);
ChronoUnit.MILLIS.between(birthDate,today);//毫秒
ChronoUnit.MICROS.between(birthDate,today);//微秒
ChronoUnit.NANOS.between(birthDate,today);
ChronoUnit.HALF_DAYS.between(birthDate,today);//相差半天数
ChronoUnit.DECADES.between(birthDate,today);//相差十年数
ChronoUnit.CENTURIES.between(birthDate,today);//相差世纪数
}
}
RecordDate:2021/08/12