Object类
java中的所有类都可以直接使用Object类中提供的一些方法。
Object的常见方法:
- toString()一般也需要重写
- 这个
equals
比较的是两个对象的地址是否一样,通常由子类重写
,用于判断对象的内容是否一样 - clone 当某个对象调用这个方法时,这个方法会复制一个一模一样的新对象返回
import java.util.Objects;
//Cloneable是一个标记接口,使得可以克隆
public class Student implements Cloneable{
private String name;
private int age;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
// this.getClass() != o.getClass()判断类型是否相等
if (o == null || this.getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
注意: 克隆分为浅克隆和深克隆,这里的属于浅克隆
浅克隆
:拷贝出的新对象,与原对象中的数据一模一样(引用类型拷贝的只是地址)
深克隆
:对象中基本类型的数据直接拷贝;对象中的字符串数据拷贝的还是地址;对象中还包含的其他对象,不会拷贝地址,会创建新对象。
Objects类
Objects是一个工具类,提供了很多操作对象的静态方法给我们使用。
常见方法:
Objects.equals()
,允许传入的第一个参数是null,更安全,而字符串的str1.equals(str2),中不允许str是null;
包装类
包装类就是把基本类型的数据包装成对象。
注意:在java中可以自动把基本类型的数据转换成包装类对象(自动装箱);也可以自动把包装类型的对象转换成对应的基本数据类型。(自动拆箱)
案例:
//1.创建Integer对象,封装基本类型数据10
Integer a = new Integer(10);
//2.使用Integer类的静态方法valueOf(数据)
Integer b = Integer.valueOf(10);
//3.还有一种自动装箱的写法(意思就是自动将基本类型转换为引用类型)
Integer c = 10;
//4.有装箱肯定还有拆箱(意思就是自动将引用类型转换为基本类型)
int d = c;
//5.装箱和拆箱在使用集合时就有体现
ArrayList<Integer> list = new ArrayList<>();
//添加的元素是基本类型,实际上会自动装箱为Integer类型
list.add(100);
//获取元素时,会将Integer类型自动拆箱为int类型
int e = list.get(0);
包装类的其他操作:
- 可以把基本类型的数据转换成字符串类型
Integer a = 23;
String s1 = Integer.toString(a);```
- 可以把**字符串类型的数值转换成数值本身对应的数据类型**
```java
String ageStr="20";
int age = Integer.parseInt(ageStr);
int age1 = Integer.valueOf(ageStr); //推荐使用
String ageStr="20.5";
double age = Double.parseDouble(ageStr);
double age = Double.valueOf(ageStr); //推荐使用
StringBuilder、StringBuffer类
-
StringBuilder代表可变字符串对象,相当于是一个容器,它里面装的字符串是可以改变的,就是用来操作字符串的。
-
StringBuilder比String更适合做字符串的修改操作,效率会更高,代码也会更简洁。
StringBuilder常见方法:
StringJoiner类
- JDK8开始才有的,跟StringBuilder一样,也是用来操作字符串的,也可以看成是一个容器,创建之后里面的内容是可变的。
- 好处: 不仅能提高字符串的操作效率,并且在有些场景下使用它操作字符串,代码会更简洁
常用方法:
案例:
import java.util.StringJoiner;
public class Test {
public static void main(String[] args) {
StringJoiner s=new StringJoiner(", ","[","]"); //构造器指定间隔符
s.add("java");
s.add("golang");
s.add("python");
System.out.println(s);
}
}
Math类
常见方法:
System类
System代表程序所在的系统,也是一个工具类。
常见方法:
案例:
public class Test {
public static void main(String[] args) {
/*
* 获取系统的时间
* 1970年到现在的毫秒值
* */
long time = System.currentTimeMillis();
System.out.println(time/1000.0+"s");
/*
* 终止当前运行的java虚拟机
* 参数作为状态码,非零状态码表示异常终止
* */
System.exit(0);
System.out.println("----------");
}
}
Runtime类
代表程序所在的运行环境。Runtime是一个单例类。
常见方法:
BigDecimal类
用于解决小数运算时,出现结果失真的问题。比如0.1+0.2结果不为0.3
常见方法:
案例:
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
// BigDecimal bigDecimal = new BigDecimal("0.1"); //直接用下面封装好的
BigDecimal a = BigDecimal.valueOf(0.1);
BigDecimal b = BigDecimal.valueOf(0.2);
BigDecimal c = a.add(b);
BigDecimal c1 = a.subtract(b);
BigDecimal c2 = a.multiply(b);
System.out.println(c);
System.out.println(c1);
System.out.println(c2);
}
}
JDK8之前传统日期和时间类
Date类
代表的是日期和时间。
常见方法:
SimpleDateFormat类
代表简单日期格式化,可以用来把日期对象、时间毫秒值格式化成我们想要的形式。
常见方法:
案例:
public class TestSimpleDateFormat {
public static void main(String[] args) {
Date date = new Date();
// 日期格式化对象
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE");
String format = simpleDateFormat.format(date);
System.out.println(format);
// -------------------------------------
String dataStr="2012-11-1";
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = simpleDateFormat1.parse(dataStr);
System.out.println(date1);
}
}
Calender类
- 代表的是系统此刻时间对应的日历。
- 通过它可以单独获取、修改时间中的年、月、日、时、分、秒等。
常见方法:
案例:
import java.util.Calendar;
import java.util.Date;
public class TestCalender {
public static void main(String[] args) {
Calendar calender = Calendar.getInstance();
System.out.println(calender);
// 获取日历中的信息
System.out.println(calender.get(Calendar.YEAR));
System.out.println(calender.get(Calendar.DAY_OF_YEAR));
// 日历中的日期对象
Date d=calender.getTime();
System.out.println(d);
// 修改日历中的某个信息
calender.set(Calendar.MONTH,9);
// 为某个信息增加或减少指定值
calender.add(Calendar.DAY_OF_YEAR,100); //在当前日期加上100天
}
}
注意: calendar是可变对象,一旦修改后其对象本身表示的时间将产生变化
JDK8后新增日期和时间类(推荐使用)
替代Calender的类
LocalDate类
代表本地日期(年,月,日,星期)
LocalTime类
代表本地时间(时,分,秒,毫秒,纳秒)
LocalDateTime类
代表本地日期,时间(年,月,日,星期,时,分,秒,毫秒,纳秒)
获取对象
常用方法:
案例:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class TestLocalDateTime {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
// 获取信息
System.out.println(now.getYear()); //获取年份
System.out.println(now.getDayOfMonth()); //获取今天是这个月第几天
// 修改信息
LocalDateTime modifyDate = now.withYear(2022);
System.out.println(modifyDate);
System.out.println(now);
// 添加或减少时间
LocalDateTime plusDays = now.plusDays(100);//加100天
LocalDateTime minusMonths = now.minusMonths(1);//减一个月
System.out.println(plusDays);
System.out.println(minusMonths);
// 获取指定日期和时间的LocalDateTime对象:
// public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour,
// int minute, int second, int nanoOfSecond)
LocalDateTime ldt1 = LocalDateTime.of(2029, 12, 12, 12, 12, 12, 1222);
LocalDateTime ldt2 = LocalDateTime.of(2029, 12, 12, 12, 12, 12, 1222);
// 6、 判断2个日期、时间对象,是否相等,在前还是在后: equals、isBefore、isAfter
System.out.println(ldt1.equals(ldt2));
System.out.println(ldt1.isAfter(ldt2));
System.out.println(ldt1.isBefore(ldt2));
// 7、可以把LocalDateTime转换成LocalDate和LocalTime
// public LocalDate toLocalDate()
// public LocalTime toLocalTime()
// public static LocalDateTime of(LocalDate date, LocalTime time)
LocalDate ld = ldt1.toLocalDate();
LocalTime lt = ldt1.toLocalTime();
LocalDateTime ldt3 = LocalDateTime.of(ld, lt);
}
}
ZoneId,ZonedDateTime类
案例:
public class TestZoneId {
public static void main(String[] args) {
// public static ZoneId systemDefault(): 获取系统默认的时区
ZoneId zoneId = ZoneId.systemDefault();
System.out.println(zoneId.getId());
System.out.println(zoneId);
// public static Set<String> getAvailableZoneIds(): 获取Java支持的全部时区Id
System.out.println(ZoneId.getAvailableZoneIds());
// public static ZoneId of(String zoneId) : 把某个时区id封装成ZoneId对象。
ZoneId zoneId1 = ZoneId.of("America/New_York");
// 2、ZonedDateTime:带时区的时间。
// public static ZonedDateTime now(ZoneId zone): 获取某个时区的ZonedDateTime对象。
ZonedDateTime now = ZonedDateTime.now(zoneId1);
System.out.println(now);
// 世界标准时间了
ZonedDateTime now1 = ZonedDateTime.now(Clock.systemUTC());
System.out.println(now1);
// public static ZonedDateTime now():获取系统默认时区的ZonedDateTime对象
ZonedDateTime now2 = ZonedDateTime.now();
System.out.println(now2);
}
}
替代 Date的类
Instant类
通过获取Instant的对象可以拿到此刻的时间,精确到纳秒。
作用:可以用来记录代码的执行时间,或用于记录用户操作某个事件的时间点。
常见方法:
案例:
public class TestInstant {
public static void main(String[] args) {
Instant now = Instant.now();
System.out.println(now);
// 获取到现在的总秒数
long second = now.getEpochSecond();
System.out.println(second);
// 不够1秒的纳秒数
int nano = now.getNano();
System.out.println(nano);
}
}
替代SimpleDateFormat的类
DateTimeFormatter类
相较于SimpleDateFormat,DateTimeFormatter是线程安全的。
常见方法:
案例:
public class TestDateTimeFormatter {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDateTime time=LocalDateTime.now();
System.out.println(time);
//格式化时间
String format = formatter.format(time);
System.out.println(format);
// 解析时间
String dateStr="2020-12-10";
LocalDate ldt = LocalDate.parse(dateStr, formatter);
System.out.println(ldt);
}
}
时间间隔类
Period类
可以用于计算两个 LocalDate对象相差的年数、月数、天数。
常见方法:
public class TestPeriod {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2029, 8, 10);
LocalDate end = LocalDate.of(2029, 12, 15);
// 1、创建Period对象,封装两个日期对象。
Period period = Period.between(start, end);
// 2、通过period对象获取两个日期对象相差的信息。
System.out.println(period.getYears());
System.out.println(period.getMonths());
System.out.println(period.getDays());
}
}
Duration类
可以用于计算两个时间对象相差的天数、小时数、分数、秒数、纳秒数;支持LocalTime、LocalDateTime、Instant等时间。
常见方法:
案例:
public class TestDuration {
public static void main(String[] args) {
LocalDateTime start = LocalDateTime.of(2025, 11, 11, 11, 10, 10);
LocalDateTime end = LocalDateTime.of(2025, 11, 11, 11, 11, 11);
// 1、得到Duration对象
Duration duration = Duration.between(start, end);
// 2、获取两个时间对象间隔的信息
System.out.println(duration.toDays());// 间隔多少天
System.out.println(duration.toHours());// 间隔多少小时
System.out.println(duration.toMinutes());// 间隔多少分
System.out.println(duration.getSeconds());// 间隔多少秒
System.out.println(duration.toMillis());// 间隔多少毫秒
System.out.println(duration.toNanos());// 间隔多少纳秒
}
}
注意:间隔秒数用duration.getSeconds()
Arrays
用来操作数组的一个工具类
常用方法:
案例:
// 4、public static setAll(double[] array, IntToDoubleFunction generator):把数组中的原数据改为新数据又存进去。
double[] prices = {99.8, 128, 100};
// 0 1 2
// 把所有的价格都打八折,然后又存进去。
Arrays.setAll(prices, new IntToDoubleFunction() {
@Override
public double applyAsDouble(int value) {
// value = 0 1 2
return prices[value] * 0.8;
}
});
System.out.println(Arrays.toString(prices));
对象数组排序
注意 Arrays.sort方法: 它无法直接对对象数组进行排序。要让对象数组也可以进行排序有两种方法。
方法一:让对象的类实现Comparable(比较规则)接口,然后重写compareTo方法,自己定义比较规则
案例:
public class Student implements Comparable<Student>{
private String name;
private double height;
private int age;
//...get、set、空参数构造方法、有参数构造方法...自己补全
// 指定比较规则
//是 this 和 o 对象进行比较
@Override
public int compareTo(Student o) {
// 约定1:认为左边对象 大于 右边对象 请您返回正整数
// 约定2:认为左边对象 小于 右边对象 请您返回负整数
// 约定3:认为左边对象 等于 右边对象 请您一定返回0
/* if(this.age > o.age){
return 1;
}else if(this.age < o.age){
return -1;
}
return 0;*/
//上面的if语句,也可以简化为下面的一行代码
return this.age - o.age; // 按照年龄升序排列
// return o.age - this.age; // 按照年龄降序排列
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", height=" + height +
", age=" + age +
'}';
}
}
方法二:在调用Arrays.sort(数组,Comparator比较器);
时,除了传递数组之外,传递一个Comparator比较器对象(采用匿名内部类)。Arrays的sort方法底层会根据Comparator比较器对象的compare方法方法的返回值是正数、负数、还是0来确定谁大、谁小、谁相等。
案例:
// 2、public static <T> void sort(T[] arr, Comparator<? super T> c)
// 参数一:需要排序的数组
// 参数二:Comparator比较器对象(用来制定对象的比较规则)
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// 制定比较规则了:左边对象 o1 右边对象 o2
// 约定1:认为左边对象 大于 右边对象 请您返回正整数
// 约定2:认为左边对象 小于 右边对象 请您返回负整数
// 约定3:认为左边对象 等于 右边对象 请您一定返回0
// if(o1.getHeight() > o2.getHeight()){
// return 1;
// }else if(o1.getHeight() < o2.getHeight()){
// return -1;
// }
// return 0; // 升序
return Double.compare(o1.getHeight(), o2.getHeight()); // 升序
// return Double.compare(o2.getHeight(), o1.getHeight()); // 降序
}
});