常用API
Object类
- 所有类都继承它
- 一切子类都可使用其方法
toString()
- 原toString方法是返回全类名+@哈希码
- 日常使用可以快捷键重写toString方法以便返回对象内容信息(JavaBean中已包含)
补充细节:用println直接打印对象时,源码层面,会自动调用对象的toString方法
equals()
-
可传入任意对象
-
原equals方法默认比较内存地址
-
//手动重写 @Override public boolean equals(0bject obj) { if(obj instanceof Student){ //判断是否是Student类型 //向下转型的目的,是为了调用子类特有的成员 Student stu = (Student) obj; return this.age == stu.age && this. name . equals(stu . name); } else { return false;| } }
-
可调用快捷键重写
@Override public boolean equals(0bject o) { // this : stu1 //o:stu2 if (this == o) { //两个对象做地址值的比较,如果地址相同,里面的内容肯定相同,直接返回为true . return true; } //代码要是能够走到这里,代表地址肯定不相同 //代码要是能够走到这里,代表stu1, 肯定不是null // stu1不是null, stu2是null, 就直接返回false // this.getClass() != o.getClass() :两个对象的字节码是否相同 //如果字节码不相同,就意味着类型不相同,直接返回false if (o == null || this.getClass() != o.getClass()) { return false; } //代码要是能够走到这里,代表字节码相同,类型肯定相同, //向下转型 Student student = (Student) 0; //比较 return this.age == student .age && 0bjects .equals(this.name, student .name); }
objects的equals方法细节
细节: 0bjects.equals方法,内部依赖于我们自己所编写的equals
好处: Objects . equals方法,内部带有非null判断public static boolean equals(Object a, object b) { /* a == b :如果地址相同,就会返回为true,这里使用的符号是短路|| ,左边为true, 右边就不执行了 -结论:如果地址相同,方法直接返回为true :如果地址不相同,就会返回false, 短路|| ,左边为false, 右边要继续执行, ------------------------------------------------------------------------------------- a!=null:假设a是null值 null != null :false &&:左边为false, 右边不执行,右边不执行, 记录着nulL值的a,就不会调用equals方法 -避免空指针异常! ------------------------------------------------------------------------------------ a!=null:假设a不是null值 stu1!=null: true && :左边为true,右边继续执行,a.equals(b), 这里就不会出现空指针异常 return (a == b) II (a != null Q& a.equals(b)); */ return (a == b)||(a != null & a.equals(b)); }
Math类 (lang包内不需要导包)
public static int abs (多种类型数) :获取参数绝对值
public static double ceil (double a) :向上取整
public static double floor (double a) :向下取整
public static int round (float a) :四舍五入
public static int max (int a,int b) :获取两个int值中的较大值/min()
public static double pow (double a, double b) :返回a的b次幂的值
public static double random () :返回值为double的随机值,范围[0.0,1.0)
System类(静态,类名直接调用)
public static void exit(int status//最好是0) 终止当前运行的Java虚拟机,非零表示异常终止
public static long currntTimeMilli() 返回当前系统的时间毫秒值形式 —— 1970年1月1日 00:00:00 到现在的毫秒值
用于计算运行时间,取开始时和结束时做差
public static void arraycopy(数据源数组,起始索引,目的地数组,目的数组的起始索引,拷贝个数) 数组拷贝
BigDecimal类
用于解决小数运算中不精确问题
创建对象
public BigDecimal(double val) //不推荐
public BigDecimal(String val) //将小数以字符串传入
BigDecimal bd1 = new BigDecimal( val: "0.1");
BigDecimal bd2 = new BigDecimal( val: "0.2");
//静态方法
public static BigDecimal value0f(double val) //以浮点传入
BigDecimal bd1 = BigDecimal. value0f(0.1);
BigDecimal bd2 = BigDecimal. value0f(0.2);
常用成员方法
public BigDecimal add(BigDecimal b) //加法
public BigDecimal subtract(BigDecimal b) //减法
public BigDecimaL multiply(BigDecimal b) //乘法
public BigDecimal divide (BigDecimal b) //除法
//重写后:
public BigDecimal divide (另一个BigDecimal对象,精确几位,舍入模式) //除法
舍入模式:四舍五入:RoundingMode.HALF_UP
上抛 RoundingMode.UP));
下抛 RoundingMode.DOWN));
doubleValue:转成double类型
包装类
将基本数据类型,包装成类,变成引用数据类型(可以调用方法快捷地解决问题)
基本数据类型 引用数据类型
byte Byte
short Short
int Integer
long Long
char Character
float Float
double Double
boolean Boolean
手动装箱:调用方法,手动将基本数据类型,包装成类
手动拆箱:调用方法,手动将包装类,拆成(转换)基本数据类型
怎么包
- public Integer(int value) :通过构造方法**(已过时不推荐)**
- public static Integer value0f(int i) :通过静态方法 (推荐)
怎么拆
public int intValue() :以int类型返回该Integer 的值
public static void main(String[] args) {
int num = 10;
Integer i1 = Integer.value0f(num);
int i = i1.intValue();
System.out.printLn(1);
}
}
自动拆装箱
基本数据类型和对应的包装类, 可以直接做运算了,不需要操心转换的问题了
int num = 10;
Integer il = num;
inti=i1;
Integer常用方法
public static String toBinaryString (int i) //转二进制
public static String to0ctalString (int i) //转八进制
public static String toHexString (int i) //转十六进制
public static int parseInt (String s) //将数字字符串,转换为数字
其他包装类类比上面的代码方法
练习题
public class IntegerTest {
/*
已知字符串String s = "10,50,30,20,40";
请将该字符串转换为整数并存入数组
随后求出最大值打印在控制台
*/
public static void main(String[] args) {
String s = "10, 50,30,20,40";
// 1.根据逗号做切割
String[] sArr = s.split( regex. ",");
// 2.准备一个整数数组,准备存储转换后的数字
int[] nums = new int[sArr .length];
// 3.遍历字符串数组
for (int i = θ; i < sArr.length; i++) {
// sArr[i] :每一个数字字符串
// 4.将数字字符串转换为整数,并存入数组
nums[i] = Integer.parseInt(sArr[i]);
}
// 5.求最大值
int max = nums[8];
for (int i = 1; i < nums.length; i++) {
if(nums[i] > max){
max = nums[i];
}
}
System. out.printLn("最大值为:" + max);
}
}
面试题
public static void main(String[] args) {
Integer i1 = 127;
Integer i2 = 127;
System. out . printLn(i1 == i2); // true
Integer i3 = -128;
Integer i4 = -128;
System. out .printLn(i3 == i4); // false
}
现象解释:自动装箱的时候
如果装箱的数据范围,是-128~127,会从底层数组中返回Integer对象
如果装箱的数据,不在-128 ~ 127 之间,会重新创建新的对象,拥有不同地址
Integer类中,底层存在一一个长度为256个大小的数组,Integer[] cache
在数组中,存储了256个Integer对象,分别是-128 ~ 127(减少内存消耗)
时间API
JDK8之前(此部分不需要深度掌握)
Date类(需要导包)
构造方法
public Date() 创建一个Date对象,代表的是系统当前此刻日期时间。
public Datel(long time) 把时间毫秒值转换成Date日期对象(从时间原点)
常见方法
public long getTime() : 返回从1970年1月1日 00:00:00走到该对象的总的毫秒数
public void setTime(long time) : 设置日期对象的时间为当前时间毫秒值对应的时间
SimpDataFormat类 用于日期格式化储存日期的格式(线程不安全)
构造方法
public SimpleDateFormat() 构造一个SimpleDateFormat,使用默认格式
public SimpleDateFormat(String pattern) 构造一-个SimpleDateFormat,使用指定的格式
格式化方法(使用前需设定好SimpDataFormat对象储存了模式)
public final String format(Date date) 将日期格式化成日期/时间字符串
public final Date parse(String source) 将字符串解析为date类型,
//创建一个日期格式化对象,使用[默认模式]
SimpleDateFormat simpLeDateFormat = new SimpLeDateFormat();
//或创建一个日期格式化对象,[手动指定模式]
SimpLeDateFormat simpLeDateFormat = new SimpLeDateFormat(pattern:"yyy年MM月dd日HH:mm:ss");
//创建Date对象, 封装此刻的时间
Date date = new Date();
//将日期对象,转换为字符串
String resutt = simpLeDateFormat. format(date);
System. out.printIn(result);
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hAHeK3KK-1681121601307)(D:\桌面\image-20230408225106287.png)]
Calendar类
代表的是系统此刻时间对应的日历,通过它可以单独获取、修改时间中的年、月、日、时、分、秒等。
创建对象(获取当前时间)
// Calendar C :抽象类
// Calendar.getInstance() :获取的是子类对象
Calendar C = Calendar.getInstance();
常用方法
public int get(int field) //取日历中的某个字段信息
// get方法的参数:Calendar中的静态常量 ex:Calendar.YEAR
//注意Calendar类的月份是0~11,想要获取常规的月份,需要对结果+ 1操作
int month = c.get(Calendar.MONTH); //获取月
System.out.printLn(month + 1);
//星期:日一二三四五六
// 1 2 3 4 5 6 7
int week = c.get(Calendar.DAY_0F_WEEK); //获取星期
System.out.printLn(week);
//修改
char[] weeks= {' ', '日','一','二', '三','四', '五','六'};
// 0 1 2 3 4 5 6 7
int weekIndex = C.get(Calendar.DAY_0F_WEEK);
System.out.println(weeks[weekIndex]);|
public void set(int field,int value) //修改日历的某个字段信息,有多种重载
Calendar C = Calendar.getInstance();
C.set(CaLendar.YEAR,2022);
public void add(int field, int amount) //为某个字段增加/减少指定的值
Calendar c = Calendar.getInstance();
c.add(Calendar.YEAR,1); //向后加一年
public final Date getTime() //获取Date类日期对象
public final setTime(Date date) //给日历设置日期对象(将Date存入Calendar)
JDK8之后(主流)
时间对象都是不可变对象,修改后返回新的时间对象,不会丢失最开始的时间
LocaLDateTime now = LocalDateTime.now();
System.out.printLn("修改前获取时间:" + now);
LocalDateTime afterTime = now.withYear(2008);
System.out.printLn("修改后获取时间: " + afterTime);
System.out.printLn("修改后获取时间: " + now); //now的时间不变
日历类
LocalDate : 年、月、日
LocalTime : 时、分、秒
LocalDateTime(主用): 年、月、日、时、分、秒、纳秒
获取对象的静态方法
pub1ic static XXXX now()//获取系统当前时间对应的该对象
LocaDate ld = LocalDate.now();
LocalTime 1t = LocalTime.now();
LocalDateTime 1dt = LocalDateTime.now();
public static Xxxx of(...)//获取指定时间的对象
LocalDate localDate1 = LocalDate.of(2099,11,11);
LocalTime localTime1 = LocalTime.of(9, 8, 59);
LocalDateTime loca1DateTime1 = LocalDateTime.of(2025, 11, 16, 14, 30, 01);
转换对象的方法
LocaLDateTime转换LocalDate,LocalTime
- toLocalDate()
- toLocalTime()
LocalDate localDate = now.toLocalDate();
LocalTime localTime = now.toLocalTime();
获取具体时间值
get(…)方法
修改方法(返回一个新对象)
withHour、withMinute、withSecond、withNano 修改时间,返回新时间对象
plusHours、plusMinutes、 plusSeconds、 plusNanos 把某个信息加多少,返回新时间对象
minusHours、minusMinutes、 minusSeconds、minusNanos 把某个信息减多少,返回新时间对象
equals、 isBefore、 isAfter 判断2个时间对象,是否相等,在前还是在后
日期格式化类(类似于正则)
DateTimeFormatter: 用于时间的格式化和解析
//构造方法指定模板
static DateTimeFormatter ofPattern(格式) //获取格式对象,返回DateTimeFormatter类的对象作为模板、
//利用模板格式化时间
String format(时间对象) //按照指定方式格式化,返回字符串
//通过模板将字符串转化成日历类
String time = "2008年08月08日";
LocalDateTime parse = LocaLDateTime.parse(time,formatter是提前有的模板); //formatter是提前有的模板
时间类
Instant : 时间戳/时间线 (会产生时差)
ZoneId : 时区
ZonedDateTime : 带时区的时间
//Instant的方法
static Instant now( ) //获取当前时间的Instant对象(标准时间)
static Instant ofXxxx(long epochMilli) //根据(秒/毫秒/纳秒)获取Instant对象
ZonedDateTime(指返回类型) atZone(ZoneId zone) //指定时区
boolean isBefore/isAfter(Instant otherInstant) //判断系列的方法
Instant minusXxx(long millisToSubtract) //减少时间系列的方法
Instant plusXxx(long millisToSubtract) //增加时间系列的方法
//获取Java中支持的所有时区
Set<String> set = ZoneId.getAvailableZoneIds();
System.out.printLn(set);
System.out.printIn(set.size());
//获取系统默认时区
ZoneId zoneId = ZoneId.systemDefault();
//静态方法获取一个指定时区
ZoneId of = ZoneId.of("Africa/Nairobi");
//Instant时间戳获取 now时间 调用atZone()方法 使用已知的of时区 生成 ZonedDateTime类带时区的时间
ZonedDateTime zonedDateTime = Instant.now().atZone(of);
static ZonedDateTime now() //获取当前时间的ZonedDateTime对象
static ZonedDateTime ofxxx(...) //获取指定时间的ZonedDateTime对象
ZonedDateTime withXxx(时间) //修改时间系列的方法
ZonedDateTime minusXxx(时间) //减少时间系列的方法
ZonedDateTime plusXxx(时间) //增加时间系列的方法
工具类(计算时间间隔)
Period : 时间间隔(年、月、日)
Duration : 时间间隔(时、分、秒、纳秒)
ChronoUnit : 时间间隔(所有单位)
Period
//此刻年月日
LocalDate today = LocalDate.now();
System.out.println(today);
//昨天年月日
LocalDate otherDate = LocaLDate.of( year: 2023,month: 2,dayOfMonth: 4);
System.out.printLn(otherDate);
//Period对象表示时间的间隔对象
Period period = Period.between(today,otherDate); //第二个参数减第一个参数
System.out.println(period.getYears());//间隔多少年
System.out.rintln(period.getMonths();//间隔的月份
System.out.println(period.getDays());//间隔的天数
System.out.println(period.toTotalMonths()); // 总月份
Duration
//此刻日期时间对象
LocalDateTime today = LocalDateTime.now();
//昨天的日期时间对象
LocalDateTime otherDate = LocaLDateTime.of(2023,2,4,0,0,0);
Duration duration = Duration.between(otherDate,today); //第二个参数减第一个参数
System.out.println(duration.toDays();//两个时间差的天数
System.out.println(duration.toHours();//两个时间差的小时数
System.out.println(duration.toMinutes());//两个时间差的分钟数
System.out.println(duration.toMillis());//两个时间差的毫秒数
System.out.println(duration.toNanos());//两个时间差的纳秒数
ChronoUnit (最需要)
System.out.printLn("相差的年数:"+ChronoUnit.YEARS.between(birthDate,today));
//其他的类比