JAVA_THIRTEEN_常用API
目录
一Object类
作用:
一 、常见方法:
public String toString()
public boolean equals(Object o)
protected Object clone ()
public static boolean equals(Object a, Object b)
包装类
StringBuilder
StringJoiner
二、 常见方法(二):
Math,System,Runtime
Math
System
Runtime
BigDecimal
LocalData ,LocalTime ,LocalDataTime
SimpleDateFormat
ZoneId,ZoneDataTime
Instant
Period
Duration
Lambda表达式
方法引用
API :应用程序接口
一Object类
作用:
是Java中所有类点的祖宗类,因此,Java中的所有类的对象都可以直接调用Object类的一些方法。
一 、常见方法:
public String toString()
返回对象字符串表示形式
存在意义:让子类重写,返回子类对象的内容
public boolean equals(Object o)
判断两个对象是否相等
存在意义:让子类重写,以便用于比较对象的内容是否相同。
-
toString()和equals()方法比较
import java.util.Objects;public class Student {private String name;private int age;public Student() {}public Student(String name, int age) {this.name = name;this.age = age;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\\'' +", age=" + age +'}';}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (!(o instanceof Student student)) return false;return getAge() == student.getAge() && Objects.equals(getName(), student.getName());}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;} }
public class Test {public static void main(String[] args) {//目标:掌握Object类提供的常用方法Student s1=new Student("韩寒",12);System.out.println(s1.toString());System.out.println();//equals 判断两个对象是否相等Student s2=new Student("韩寒",12);System.out.println(s1==s2); // falseSystem.out.println(s1.equals(s2)); //true} }
protected Object clone ()
对象克隆
当某个对象调用这个方法时,这个方法会返回一个一模一样的对象返回
浅克隆
拷贝出新对象时,与原对象中的数据一模一样(引用 类型拷贝的只是地址)
深克隆
对象中基本数据类型直接拷贝
对象中字符串数据拷贝的还是地址
对象中包含其它对象时,不会拷贝地址,会创建对象
-
对象克隆
public class User implements Cloneable{private int id;private String name;private String password;private double[] arr;public User() {}public User(int id, String name, String password, double[] arr) {this.id = id;this.name = name;this.password = password;this.arr = arr;}@Overrideprotected Object clone() throws CloneNotSupportedException {User u2=(User) super.clone();u2.arr=u2.arr.clone();return u2; //深克隆// return super.clone(); //浅克隆}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public double[] getArr() {return arr;}public void setArr(double[] arr) {this.arr = arr;} }
public class Test2 {public static void main(String[] args) throws CloneNotSupportedException {User u1=new User(1,"猎人","123",new double[]{123,123});System.out.println(u1.getId());System.out.println(u1.getName());System.out.println(u1.getArr());System.out.println("--------------");User u2=(User) u1.clone();System.out.println(u2.getId());System.out.println(u2.getName());System.out.println(u2.getArr());} }
public static boolean equals(Object a, Object b)
先做非空判断,再比较两个对象
public static boolean isNull(Object obj)
判断对象是否为null,为null返回true,反之
public static boolean nonNull(Object obj)
判断对象是否不为null,不为null则返回true,反之
-
equals ,isNull, nonNull
public class Test3 {public static void main(String[] args) {//目标:掌握Object类提供的常用方法String s1="123456";String s2="abcdef";String s3="123456";String s4=null;//equlasSystem.out.println(s1==s2);//false//更安全,更好!System.out.println(Objects.equals(s1,s2)); //falseSystem.out.println(Objects.equals(s1,s3)); //true//isNullSystem.out.println("----------------");System.out.println(Objects.isNull(s1));//falseSystem.out.println(Objects.isNull(s4));//true//nonNullSystem.out.println("----------------");System.out.println(Objects.nonNull(s4));//falseSystem.out.println(Objects.nonNull(s1));//true} }
包装类
指的是把基本类型的数据包装成对象
常见操作:
可以把基本类型的数据转换成字符串类型
可以把字符串类型的数值转换成数值本身对应的数据类型
-
包装类
public class Test4 {public static void main(String[] args) {//目标,掌握包装类的使用Integer a1=Integer.valueOf(12);System.out.println(a1);//自动装箱Integer a2=12;//自动拆箱int a3=a2;//泛型和集合不支持基本数据类型,只支持引用类型数据ArrayList<Integer> list=new ArrayList<>();list.add(12); //自动装箱list.add(13); //自动装箱int ls=list.get(1); //自动拆箱System.out.println("---------------------");//1.基本类型转换成字符串Integer a=23;String rs1=Integer.toString(a);//"23"System.out.println(rs1+1); //231String rs2=a.toString(); //"23"System.out.println(rs2+1); //"231"//2.字符串类型数值转换对应的基本数据类型String s1="123";int age=Integer.parseInt(s1); //123int b=Integer.valueOf(s1); //123System.out.println(age+1); //124System.out.println(b+1); //124String s2="12.5";double age2=Double.parseDouble(s2);//12.5double b2=Double.valueOf(s2); //12.5System.out.println(age2+1); //13.5System.out.println(b2+1); //13.5} }
StringBuilder
StringBuilder 代表可变字符串对象,相当于是一个容器,它里面装的字符串时可变的,就是用来操纵字符串的。
好处:StringBuilder比String更适合做字符串的修改操作,效率会更高,代码也会更加简洁
StringBuilder适合进行频繁操作字符串
注意:
String Builder 和String Buffer 的用法是一摸一样的
但String Builder 是线程不安全的,StringBuffer是线程安全的
-
StringBuilder常用操作
public class Test {public static void main(String[] args) {StringBuilder s=new StringBuilder();s.append("java1");s.append("java2");s.append("java3");System.out.println(s); //java1java2java3//1.返回字符串的长度System.out.println(s.length()); //15//2.支持链式编程s.append("java4").append("java5");System.out.println(s); //java1java2java3java4java5//3.反转操作s.reverse();System.out.println(s); //5avaj4avaj3avaj2avaj1avaj//4.把StringBuilder转换成StringString rs=s.toString();System.out.println(rs); //5avaj4avaj3avaj2avaj1avaj} }
StringJoiner
和StringBuilder一样,也是用来操纵字符串的,也可以看成是一个容器,创建后内容是可变的。
好处:
不仅能提高字符串的操作效率,并且有些场景下使用它操作字符串,代码会会更加简洁
public StringJoiner(间隔符号) 创建一个StringJoiner对象,指定拼接时的家家间隔符号
public StringJoiner(间隔符号,开始符号,结束符号) 创建一个StringJoiner对象,指定拼接时的间隔符号,开始符号,结束符号
-
StringJoiner基本操作
public class Test {public static void main(String[] args) {//StringJoiner 可以在开始声明间隔符,开始符和结尾符。StringJoiner s=new StringJoiner(",","{","}");s.add("1");s.add("2");s.add("3");System.out.println(s); //{1,2,3}System.out.println(s.length()); //7System.out.println(s.toString()); //{1,2,3}}}
二、 常见方法(二):
Math,System,Runtime
-
Math,System,Runtime举例代码
Math
public class Test {public static void main(String[] args) {//1.public static int abs(int a) 取绝对值System.out.println(Math.abs(-12)); //12//2.public static double floor(double a) 向下取整System.out.println(Math.floor(3.14)); //3.0//3.public static double ceil(double a) 向上取整System.out.println(Math.ceil(3.14)); //4.0//4.public static int round(double a) 四舍五入System.out.println(Math.round(3.14)); //3System.out.println(Math.round(3.54)); //4//5.public static int max(int a,int b) 取较大值// public static int min(int a,int b) 取较小值System.out.println(Math.max(12,13)); //13System.out.println(Math.min(12,13)); //12//6.public static double pow(double a,double b) 取次方System.out.println(Math.pow(2,3)); //8//7.public static double random() 取随机数 [0.0,1.0) 包前不包后System.out.println(Math.random());Random random=new Random();int s= random.nextInt(10);System.out.println(s);} }
System
public class Test {public static void main(String[] args) {//1.public static void exit(int status)//System.exit(0); //人为终止虚拟机//2.public static long currentTimeMillis()long time=System.currentTimeMillis(); //获取当前系统时间 毫秒值System.out.println(time);for (int i = 0; i < 1000000; i++) {System.out.println("输出:"+i);}long time2=System.currentTimeMillis();System.out.println((time2-time)/1000.0);} }
Runtime
import java.io.IOException;public class Test {public static void main(String[] args) throws IOException, InterruptedException {//1.public static Runtime getRuntime() 返回Java应用程序关联的运行时对象Runtime r=Runtime.getRuntime();//2.public static void exit(int status) 终止当前运行的虚拟机//r.exit(0);//3.public int availableProcessors() 获取虚拟机使用的处理器数System.out.println(r.availableProcessors());//4.public long totalMemory() 返回Java虚拟机中的内存总量System.out.println(r.totalMemory()/1024.0/1024.0+"MB");//5.public long freeMemory() 返回Java虚拟机中的可用内存量System.out.println(r.freeMemory()/1024.0/1024.0+"MB");//6.public Process exec(String command) 启动某个程序,并返回代表该程序的对象r.exec("D:\\\\腾讯会议\\\\wemeetapp.exe");Thread.sleep(1000); //休眠1s} }
BigDecimal
作用:解决小数点失真问题
-
BigDecimal举例代码
public class BigDecimalDemo1 {public static void main(String[] args) {//目标:掌握BigDecimal的使用,解决小数点失真问题double a=0.1;double b=0.2;double c=a+b;System.out.println(c);System.out.println("-------------------");//1.把他们变成字符串封装成BigDecimal对象来运算 // BigDecimal a1=new BigDecimal(Double.toString(a)); // BigDecimal b1=new BigDecimal(Double.toString(b));BigDecimal a1=BigDecimal.valueOf(a);BigDecimal b1=BigDecimal.valueOf(b);BigDecimal c1=a1.add(b1); //加法BigDecimal c2=a1.subtract(b1); //减法BigDecimal c3=a1.multiply(b1); //乘法BigDecimal c4=a1.divide(b1,6); //除法,可精确到小数位数System.out.println(c1);System.out.println(c2);System.out.println(c3);System.out.println(c4);}}
LocalData ,LocalTime ,LocalDataTime
LocalData:代表本地日期()
LocalTime:代表本地时间()
LocalDataTime:代表本地日期,时间()
-
LocalData ,LocalTime ,LocalDataTime
public class Test_localData {public static void main(String[] args) {//1.获取本地日期对象(不可变对象)LocalDate ld=LocalDate.now(); //年,月,日System.out.println(ld);//2.获取日期对象中的信息int year=ld.getYear();int month=ld.getMonthValue();int day=ld.getDayOfMonth();int dayOfYear=ld.getDayOfYear();int dayOfWeek=ld.getDayOfWeek().getValue(); //星期几//2.直接修改某个信息LocalDate ld2=ld.withYear(2099);LocalDate ld3=ld.withMonth(12);LocalDate ld4=ld.withDayOfMonth(30);LocalDate ld5=ld.withDayOfYear(100);//3.把某个信息加多少LocalDate ld6=ld.plusYears(2);LocalDate ld7=ld.plusMonths(2);LocalDate ld8=ld.plusDays(2);//4.把某个信息减多少LocalDate ld9=ld.minusYears(2);LocalDate ld10=ld.minusMonths(2);//5.获取指定日期的LocalData对象LocalDate ld11=LocalDate.of(2020,12,10);LocalDate ld12=LocalDate.of(2010,12,10);//6.判断两个日期是否相等,在前还是在后System.out.println(ld9.equals(ld10)); //falseSystem.out.println(ld9.isAfter(ld10)); //falseSystem.out.println(ld9.isBefore(ld10)); //true} }
public class Test2_localTime {public static void main(String[] args) {//1.获取本地时间对象(不可变对象)LocalTime ld=LocalTime.now(); //时,分,秒,纳秒System.out.println(ld);//2.获取时间对象中的信息int hour=ld.getHour();int minute=ld.getMinute();int second=ld.getSecond();int nano=ld.getNano();//2.直接修改某个信息LocalTime ld2=ld.withHour(2099);LocalTime ld3=ld.withMinute(209);LocalTime ld4=ld.withSecond(20);LocalTime ld5=ld.withNano(20);//3.把某个信息加多少LocalTime ld6=ld.plusHours(2);LocalTime ld7=ld.plusMinutes(2);LocalTime ld8=ld.plusSeconds(2);LocalTime ld9=ld.plusNanos(2);//4.把某个信息减多少LocalTime ld10=ld.minusHours(2);LocalTime ld11=ld.minusMinutes(2);LocalTime ld12=ld.minusSeconds(2);LocalTime ld13=ld.minusNanos(2);//5.获取指定日期的LocalData对象LocalTime ld14=LocalTime.of(12,12,10);LocalTime ld15=LocalTime.of(2,12,10);//6.判断两个日期是否相等,在前还是在后System.out.println(ld9.equals(ld10)); //falseSystem.out.println(ld9.isAfter(ld10)); //falseSystem.out.println(ld9.isBefore(ld10)); //true} }
public class Test3_localDataTime {public static void main(String[] args) {//获取年月日时分秒纳秒LocalDateTime ldt=LocalDateTime.now();System.out.println(ldt);//7.可以把LocalDataTime转换成LocalData和LocalTimeLocalDate ld=ldt.toLocalDate();LocalTime lt=ldt.toLocalTime();LocalDateTime ldt10=LocalDateTime.of(ld,lt);System.out.println(ld);System.out.println(lt);System.out.println(ldt10);} }
SimpleDateFormat
-
SimpleDateFormat
// 7. 字符串 转换 Date SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String format = simpleDateFormat.format(new Date()); Date date = simpleDateFormat.parse(format);// 8. 字符串 转 LocalDateTime,LocalDate,LocalTime DateTimeFormatter localDateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime localDateTime3 = LocalDateTime.parse("2020-11-11 00:00:00",localDateTimeFormatter); //2020-11-11T00:00 String formatLocalDateTime = localDateTime3.format(localDateTimeFormatter);// 2020-11-11 00:00:00DateTimeFormatter localDateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate date1 = LocalDate.parse("2020-11-11",localDateFormat);// 2020-11-11 String localDateString = date1.format(localDateFormat);// 2020-11-11DateTimeFormatter localTimeFormat = DateTimeFormatter.ofPattern("HH:mm:ss"); LocalTime time = LocalTime.parse("00:00:00",localTimeFormat); //00:00 String localTimeString = time.format(localTimeFormat);//00:00:00
ZoneId,ZoneDataTime
-
ZoneId,ZoneDataTime
public class ZoneId_time {public static void main(String[] args) {//1.ZoneId的常用方法ZoneId zoneId=ZoneId.systemDefault(); //获取系统默认时区System.out.println(zoneId);//2.获取Java支持的全部时区System.out.println(zoneId.getAvailableZoneIds());//3.把某个时区Id封装成zoneId对象ZoneId zoneId1=zoneId.of("America/Cuiaba");System.out.println(zoneId1);ZonedDateTime now=ZonedDateTime.now(zoneId1); //带时区的时间System.out.println(now);ZonedDateTime now1=ZonedDateTime.now(Clock.systemUTC()); //世界标准时间System.out.println(now1);ZonedDateTime now2=ZonedDateTime.now(); //默认时间System.out.println(now2);} }
Instant
作用:
可以用来记录代码的执行时间
-
Instant
public class instant_time {public static void main(String[] args) {//1.创建instant对象Instant now=Instant.now();//不可变对象System.out.println(now);//2.获取总秒数long second=now.getEpochSecond();System.out.println(second);//3.不够一秒的纳秒数int nano=now.getNano();System.out.println(nano);} }
Period
可以计算两个LocalData对象相差的年数,月数,天数。
-
Period
public class Test7_Period {public static void main(String[] args) {LocalDate start=LocalDate.of(2029,8,11);LocalDate end=LocalDate.of(2029,12,10);//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、LocalDataTime、Instant等时间。
-
Duration
public class Test8_Duration {public static void main(String[] args) {LocalDateTime start=LocalDateTime.of(2055,12,16,10,11,12);LocalDateTime end=LocalDateTime.of(2056,12,16,10,11,12);//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.toSeconds());//秒System.out.println(duration.toMillis());//毫秒System.out.println(duration.toNanos());//纳秒} }
Lambda表达式
作用:用于简化匿名内部类的代码写法
格式
(被重写方法的形参列表)->{被重写方法的方法体代码
};
前提:
Lambda表达式并不是说简化全部匿名内部类的写法,只能简化函数式接口的匿名内部类。
函数式接口里只有一个抽象方法的接口,
接口上面如果有一个@FunctionalInterface的注解,必定是函数式接口
Lambda表达式的省略写法
参数类型可以省略不写
如果只有一个参数,参数类型可以省略,同时()也可以省略。
如果lambda表达式中的方法体代码只有一行代码,可以省略大括号不写,同时要省略分号!此时,如果这行代码是return语句,也必须去掉return不写。
-
Lambda表达式举例代码
import org.example.d1_object.Student;import java.util.Arrays; import java.util.Comparator; import java.util.function.IntToDoubleFunction;public class Test5_Lambda {public static void main(String[] args) {double[] price={123,100.5,155};System.out.println(Arrays.toString(price));// Arrays.setAll(price, new IntToDoubleFunction() { // @Override // public double applyAsDouble(int value) { // return price[value]*0.8; // } // });// Arrays.setAll(price,(int value)->{ // return price[value]*0.8; // });// Arrays.setAll(price,value->{ // return price[value]*0.8; // });Arrays.setAll(price,value-> price[value]*0.8);System.out.println(Arrays.toString(price));Student []students=new Student[4];students[0]=new Student("韩寒",13);students[1]=new Student("韩白",18);students[2]=new Student("韩那安",16);students[3]=new Student("韩非",19);System.out.println(Arrays.toString(students)); // Arrays.sort(students, new Comparator<Student>() { // @Override // public int compare(Student o1, Student o2) { // return o1.getAge()-o2.getAge(); // } // });// Arrays.sort(students,(Student o1, Student o2)->{ // return o1.getAge()-o2.getAge(); // });Arrays.sort(students,(o1, o2)-> o1.getAge()-o2.getAge());System.out.println(Arrays.toString(students));} }//输出 //[123.0, 100.5, 155.0] //[98.4, 80.4, 124.0] //[Student{name='韩寒', age=13}, Student{name='韩白', age=18}, Student{name='韩那安', age=16}, Student{name='韩非', age=19}] //[Student{name='韩寒', age=13}, Student{name='韩那安', age=16}, Student{name='韩白', age=18}, Student{name='韩非', age=19}]
方法引用
作用:进一步简化Lambda表达式的,方法引用的标志符号为”::”
静态方法的引用
如果某个Lambda表达式里只是调用一个静态方法,并且前后参数的形式一致,就可以使用静态方法引用。
实例方法的引用
-
静态方法和实例方法的引用的举例代码
import org.example.d1_object.Student;import java.util.Arrays; import java.util.Comparator;public class Test9 {public static void main(String[] args) {Student[] students = new Student[4];students[0] = new Student("韩寒", 13);students[1] = new Student("韩白", 18);students[2] = new Student("韩那安", 16);students[3] = new Student("韩非", 19);System.out.println(Arrays.toString(students)); // Arrays.sort(students, new Comparator<Student>() { // @Override // public int compare(Student o1, Student o2) { // return o1.getAge() - o2.getAge(); // } // });//静态方法Arrays.sort(students, compareByData::compareByAge); //升序System.out.println(Arrays.toString(students));//实例方法compareByData compare=new compareByData();Arrays.sort(students, compare::compareByAgeDesc); //降序System.out.println(Arrays.toString(students));} }
import org.example.d1_object.Student;public class compareByData {public static int compareByAge(Student o1,Student o2){return o1.getAge()-o2.getAge();}public int compareByAgeDesc(Student o1,Student o2){return o2.getAge()-o1.getAge();} }
特定类型方法的引用
如果某个lambda表达式里只是调用一个实例方法,并且前面参数列表中的第一个参数是作为方法的主调,后面的所有参数都是作为该实例方法的入参的,则此时就可以使用特定类型的方法引用。
-
特定类型方法的引用
import java.util.Arrays; import java.util.Comparator;public class Test1 {public static void main(String[] args) {String names[]={"Abd","Boy","Court","andy","Yea","pou"};Arrays.sort(names);System.out.println(Arrays.toString(names));// Arrays.sort(names, new Comparator<String>() { // @Override // public int compare(String o1, String o2) { // return o1.compareToIgnoreCase(o2); // } // });//特定类型的方法引用Arrays.sort(names,String::compareToIgnoreCase);System.out.println(Arrays.toString(names));} }
构造器引用
如果某个lambda表达式里只是在创建对象,并且前后参数一致,就可以使用构造器使用。
-
构造器引用
import java.util.Arrays;public class Test2 {public static void main(String[] args) {//1.创建这个接口的内部类对象 // CreateCar createCar=new CreateCar() { // @Override // public Car create(String name, double price) { // return new Car(name,price); // } // };CreateCar cc=Car::new;Car c=cc.create("卡车",1000);System.out.println(c.getName()+c.getPrice());} } interface CreateCar{Car create(String name,double price); }
public class Car {private String name;private double price;public Car() {}public Car(String name, double price) {this.name = name;this.price = price;}public String getName() {return name;}public void setName(String name) {this.name = name;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;} }