Date类
Date类是在Java中获取日期时间最简单的一个类,可以通过直接实例化对象的方式获得当前的日期时间。得到的日期时间是国外的格式。Date类没有什么特殊的用法,就是简单的获取当前的日期时间。
public class DateTest01 {
public static void main(String[] args) {
//通过默认的构造方法进行实例化对象
Date date = new Date();
System.out.println(date); //Sat Oct 01 20:09:32 CST 2022
//得到当前日期时间的毫秒值
long time = date.getTime();
System.out.println(time);//1664626172682
//通过有参构造的方式进行实例化对象
Date dateA = new Date(System.currentTimeMillis()-10000);
System.out.println(dateA);//Sat Oct 01 20:14:48 CST 2022
//通过默认的构造方法进行实例化对象
Date dateB = new Date();
System.out.println(dateB);//Sat Oct 01 20:14:58 CST 2022
//得到两个时间毫秒值的差
long subTime = dateA.getTime() - dateB.getTime();
//10000
System.out.println(subTime);
//判断两个时间的大小
boolean t = dateA.after(dateB);
boolean t2 = dateA.before(dateB);
System.out.println(t);
System.out.println(t2);
}
}
Calendar日历类
主要用于日期时间之外的日历相关的操作。Calendar类是一个抽象类,是所有日期类的模板,提供一些日历通用的方法,但是Calendar类本身不可以进行实例化,需要通过静态的getInstance()
方法获取实例化对象。
getInstance()方法可以根据不同的TimeZone、Locale来获取对应的Calendar。
public class Calendar_test {
public static void main(String[] args) {
//通过getInstance()获取默认的Calendar实例
Calendar calendar = Calendar.getInstance();
//通过Calendar的getTime()方法得到Date类对象,底层是返回的是Date类的有参构造方法
Date date = calendar.getTime();
System.out.println(date); //Sat Oct 01 20:53:39 CST 2022
}
}
field就是Calendar类中定义的常量,分别代表年、月、日、时、分、秒等日期,以 Calendar.YEAR、Calendar.MONTH... 等等,类型是int。
方法 | |
---|---|
void add(int field, int amount) | 根据规则field,给指定的终端添加amount值 |
int get(int field) | 根据规则field,获得对应字段的值,从0开始 |
int getActualMaximum(int field) | 根据规则field,获得对应字段的最大值,从0开始 |
int getActualMinimum(int field) | 根据规则field,获得对应字段的最小值,从0开始 |
void set(int field, int value) | 给对应的日历字段设置值 |
void set(int year, int month, int date) | 设置年、月、日的值 |
void set(int year, int month, int date, int hour, int minute, int secend) | 设置年、月、日、时、分、秒的值 |
Calendar.getInstance(); | 返回Calendar的默认实例 |
public class Calendar_test {
public static void main(String[] args) {
//创建一个默认的Calendar实例
Calendar calendar = Calendar.getInstance();
//获得日期时间的年份
int year = calendar.get(Calendar.YEAR);
//获得日期时间的月份,从0开始
int month = calendar.get(Calendar.MONTH);
System.out.println(year); //2022
System.out.println(month); //9
//给日期时间的年份加3
calendar.add(Calendar.YEAR,3);
//获得加3年后的年份
int year2 = calendar.get(Calendar.YEAR);
System.out.println(year2);//2025
//给日期时间的月份加2
calendar.add(Calendar.MONTH,2);
//获得加2个月后的月份
int month2 = calendar.get(Calendar.MONTH);
System.out.println(month2); //11
//设置日期时间的年份的值为1999
calendar.set(Calendar.YEAR,1999);
//获得设置完日期时间年份的值
int year3 = calendar.get(Calendar.YEAR);
System.out.println(year3);//1999
//设置年月日的值
calendar.set(2000,5,3);
//获得设置完日期时间年份的值
int year4 = calendar.get(Calendar.YEAR);
//获得设置完日期时间月份的值
int month3 = calendar.get(Calendar.MONTH);
System.out.println(calendar.getTime()); // Sat Jun 03 21:58:22 CST 2000
System.out.println(year4); //2000
System.out.println(month3); //5
}
}
DateFormat
DateFormat是一个抽象类,有三个方法获得对应的格式化器对象。只是一个格式化类,用于对日期进行格式化,本身无法获取日期时间。
获取DateFormat实例化对象的方法 | |
---|---|
DateFormat.getDateInstance() | 返回一个默认的日期格式化器对象 |
DateFormat.getDateInstance(int style) | 返回一个指定格式的日期格式化器对象 |
DateFormat.getDateInstance(int style, int locale) | 返回一个指定格式和时区的日期格式化器对象 |
DateFormat.getTimeInstance() | 返回一个默认的时间格式化器对象 |
DateFormat.getTimeInstance(int style) | 返回一个指定格式的时间格式化器对象 |
DateFormat.getTimeInstance(int style, int locale) | 返回一个指定格式和时区的时间格式化器对象 |
DateFormat.getDateTimeInstance() | 返回一个默认的日期时间格式化器对象 |
DateFormat.getDateTimeInstance(int style) | 返回一个指定格式的日期时间格式化器对象 |
DateFormat.getDateTimeInstance(int style, int locale) | 返回一个指定格式和时区的日期时间格式化器对象 |
通过调用上面的三个方法的重载,可以指定日期时间的格式style,分别是 DateFormat.FULL
、DateFormat.LONG
、DateFormat.MEDIUM
、 DateFormat.SHORT
四种静态常量。
还可以通过传入时区静态常量locale,指定时区,Locale.CHINA
、Locale.ENGLISH
...等等
DateFormat实例化对象有两个主要的方法,实现格式化操作。
方法 | |
---|---|
String format(Date date); | 把日期类对象格式化为指定格式的字符串 |
Date parse(String str); | 把字符串格式转化为Date类对象,但是字符串有格式要求,必须和格式化器对象的格式style一致 |
public class DateFormat_Test {
public static void main(String[] args) {
//创建一个Date类对象
Date date = new Date();
System.out.println(date);//Sat Oct 01 22:49:14 CST 2022
//获取一个默认的日期格式化器对象
DateFormat dateFormat = DateFormat.getDateInstance();
//把Date类对象格式化为String类型字符串,因为是默认的格式化器对象,所以字符串的格式也是默认的格式。
String d = dateFormat.format(date);
System.out.println(d); //2022-10-1
//获取一个DateFormat.LONG类型格式的日期格式化器对象
DateFormat dateFormat1 = DateFormat.getDateInstance(DateFormat.LONG);
//把Date类对象以DateFormat.LONG的格式进行格式化
String d2 = dateFormat1.format(date);
System.out.println(d2); //2022年10月1日
//获取一个DateFormat.FULL类型格式和中国时区的日期格式化器对象
DateFormat dateFormat2 = DateFormat.getDateInstance(DateFormat.FULL, Locale.CHINA);
//把Date类对象以DateFormat.FULL和中国时区的格式进行格式化
String d3 = dateFormat2.format(date);
System.out.println(d3); //2022年10月1日 星期六
String str = "2022年10月1日";
//字符串必须和格式化器对象的格式一致
DateFormat dateFormat3 = DateFormat.getDateInstance(DateFormat.LONG);
//把正确格式的字符串格式化为Date类对象
Date date1 = dateFormat3.parse(str);
System.out.println(date1);//Sat Oct 01 00:00:00 CST 2022
}
}
SimpleDateFormat
SimpleDateFormat类是DateFormat抽象类的子类。可以通过实例化创建类对象。在实例化的时候需要给构造方法传入一个字符串类型的格式,用来作为格式化的格式。
常用方法 | |
---|---|
String format(Date date) | 把Date类对象格式化为字符串 |
Date parse(String str) | 把字符串格式化为Date类对象,字符串的格式必须和格式化器对象的格式一致 |
public class SampleDateFormat_Test {
public static void main(String[] args) throws ParseException {
//把Date类对象格式化为特定格式的String字符串
//创建一个Date类对象
Date date = new Date();
//创建一个日期格式化类对象,格式为"yyyy-MM-dd HH:mm:ss"
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//把Date类对象格式化为String字符串
String str = simpleDateFormat.format(date);
System.out.println(str); //2022-10-01 23:40:24
String str1 = "2000-05-03 28:22:58";
//把字符串格式化为Date类对象
Date date1 = simpleDateFormat.parse(str1);
System.out.println(date1); //Thu May 04 04:22:58 CST 2000
}
}
LocalDate
该类表示不带时区的日期类,通过LocalDate.now()
来获得当前日期。
public class LocalDate_Test {
public static void main(String[] args) {
//通过静态方法now()来获得当前日期。
LocalDate localDate = LocalDate.now();
System.out.println(localDate); //2022-10-01
}
}
LocalTime
该类表示不带时区的时间类,通过LocalTime.now()
来获得当前日期。
public class LocalDate_Test {
public static void main(String[] args) {
//通过静态方法now()来获得当前时间。
LocalTime localTime = LocalTime.now();
System.out.println(localTime); //23:51:33.772
}
}
LocalDateTime
该类表示不带时区的日期时间类,通过LocalDateTime.now()
来获得当前日期。
public class LocalDate_Test {
public static void main(String[] args) {
//通过静态方法now()来获得当前日期时间。
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime); //2022-10-01T23:53:01.237
}
}
AutoCloseable接口
在实际项目中,一般都会用到一些资源,例如文件资源,网络资源等,都需要对资源进行释放关闭。
AutoCloseable接口就是自动关闭的处理接口。
当一个资源类实现了该接口close方法,在使用try-catch-resources语法创建的资源抛出异常后,JVM会自动调用close 方法进行资源释放,当没有抛出异常正常退出try-block时候也会调用close方法。
示例代码一:没有抛出异常情况
//创建一个类实现AutoCloseable接口,重写接口的close()方法,在程序执行完后,会调用这个重写的close()方法进行资源关闭和释放。
public class Read implements AutoCloseable{
//自定义的方法
public void read(){
System.out.println("Read Java");
}
@Override
public void close() throws Exception {
System.out.println("close方法关闭资源!");
}
}
//测试类,当前是没有出现异常,但是还是会执行close()方法。
public class Test {
public static void main(String[] args) {
try(Read read = new Read();){
read.read();
}catch (Exception e){
System.out.println("异常catch");
}
}
}
示例代码二:抛出异常情况
public class Read implements AutoCloseable{
public void read(int i){
if (i == 1){
//抛出异常
throw new RuntimeException("出现异常");
}
//程序会直接结束,不会执行
System.out.println("Read Java");
}
@Override
public void close() throws Exception {
System.out.println("close方法关闭资源!");
}
}
public class Test {
public static void main(String[] args) {
try(Read read = new Read();){
read.read(1);
}catch (Exception e){
System.out.println("异常catch");
}
}
}
总结:
-
只有在try的()中声明的资源,close方法才会被调用,并且当对象销毁的时候close也不会被调用。
-
使用try-catch-resources结构,无论是否抛出异常,在try-block执行完毕后都会调用资源的close方法。
-
使用try-catch-resources结构创建多个资源,try-block执行完毕后调用的close方法的顺序与创建资源顺序相反。
-
使用try-catch-resources结构,try-block块抛出异常后先执行close方法,然后在执行catch里面的代码,最后才是finally.
-
使用try-catch-resources结构,无须显示调用close()方法进行资源释放。
Runtime类
Runtime类表示Java程序的运行时环境,每一个Java程序都有一个对应的Runtime类实例化对象。程序通过这个对象与运行时环境相连。
Runtime类是单例模式,不可以自己创建实例化对象,每一个程序在底层JVM
上都会自动创建一个Runtime类的实例化对象,只可以通过静态的getRuntime()方法获取。
所有的Java程序都必须运行在JVM
上,每一个Java程序都会运行在一个单独的JVM
进程上,每一个JVM
进程都有一个Runtime()类的实例化对象。在Runtime()类中包含了JVM
进程的信息,可以对系统底层进行操作和控制。
在实际开发中,对于Runtime类来讲比较重要的操作是对内存信息的动态获取,因为Java程序的正常运行是依靠内存来完成的,所以Java程序需要保证内存是否可以保证程序的正常运行。
Runtime类的常用方法:
方法 | |
---|---|
Runtime.getRuntime() | 返回一个Runtime类的实例化对象 |
Process exec(String command) | 根据command开启新的进程,command就是进程的名称 |
long maxMemory() | 获得当前程序最大内存,结果是字节,默认是物理内存的1/4 |
long totalMemory() | 获得当前程序可用内存,结果是字节默认是物理内存的1/64 |
long freeMemory() | 获得当前程序空余内存,结果是字节 |
long availableprocessors() | 获得处理器数量 |
void gc() | 通知系统进行垃圾回收 |
void load(String fileName) | 加载文件 |
void loadLibrary(String libName) | 加载动态链接库 |
void destory() | 销毁进程 |
public class Runtime_Test {
public static void main(String[] args) throws IOException {
//获取Runtime实例化对象
Runtime runtime = Runtime.getRuntime();
//开启记事本进程
Process process = runtime.exec("notepad.exe");
System.out.println("处理器数量="+runtime.availableProcessors());
System.out.println("当前程序的最大内存数="+runtime.maxMemory());
System.out.println("当前程序的可用内存数="+runtime.totalMemory());
System.out.println("当前程序的空余内存数="+runtime.freeMemory());
//通知系统进行垃圾回收
runtime.gc();
}
}
整个JVM
进程的最大内存(maxMemory) > 可用内存(totalMemory) > 剩余内存(freeMemory),如果剩余内存不足,可用内存也会进行动态的扩充
在Java中,所有的GC属于守护线程,主要的目的是进行垃圾的收集以及堆内存的空间释放。
如果要进行垃圾回收,有两种方式进行,一种是JVM
的自动回收机制,还有就是通过调用Runtime类的gc()方法进行手动的垃圾回收,建议通过JVM
的自动回收机制进行垃圾回收。
ProcessHandle接口
通过ProcessHandle接口可以获得进程的一些信息。算是Runtime类的一个功能补充,配合Runtime类一起使用。
ProcessHandle还提供了一个内部类ProcessHandle.Info类,用来获取进程的参数、命令、运行时间等参数。
public class Runtime_Test {
public static void main(String[] args) throws IOException {
//获取Runtime类实例化对象
Runtime runtime = Runtime.getRuntime();
//开启一个进程
Process p = runtime.exrc("notepad.exe");
//通过进程对象,创建ProcessHandle的实例化对象
ProcessHandle pro_dle = p.toHandle();
System.out.println("进程是否在运行:"+pro_dle.isAlive());
System.out.println("进程id:"+pro_dle.pid());
System.out.println("父进程:"+pro_dle.parent());
//通过ProcessHandle的实例化对象,获取ProcessHandle.Info类的实例化对象
ProcessHandle.Info info = pro_dle.info();
System.out.println("进程命令:"+info.command());
System.out.println("进程参数:"+info.arguments());
System.out.println("进程启动时间:"+info.startInstant());
System.out.println("进程累计运行时间:"+info.totalCpuDruation());
}
}
System类
System类是在Java开发过程中最常见的一种系统类,主要是执行一些系统命令。
方法 | |
---|---|
System.currentTimeMillis() | 返回当前的时间戳,毫秒值。 |
System.exit(int status) | 结束进程,底层调用的是Runtime类的exit()方法 |
System.gc() | 通知系统进行垃圾回收,底层调用的是Runtime类的gc()方法 |
在System类的使用时,通过currentTimeMillis()方法,获取程序执行前和执行后的时间戳,然后计算出程序执行的时间。
currentTimeMillis()方法实际上是计算出当前时间的毫秒值到1970年1月1日
的差值。
public class System_Test {
public static void main(String[] args) throws Exception {
//程序执行前的时间戳
long time1 = System.currentTimeMillis();
Thread.sleep(10000);
//程序执行后的时间戳
long time2 = System.currentTimeMillis();
long sub = (time2 - time1);
}
}
HashCode()方法
返回对象的哈希码值。
哈希值是根据对象的地址或字符串或数字,通过hash算法计算出来的int类型的数值。
一般情况下,相同的对象返回相同的哈希码值。
finalize()方法
在Java程序中提供了GC()方法进行垃圾回收,这样一来,只要发现堆内存不足的时候,就会进行垃圾回收,释放内存空间。但是如果某些类的对象在回收之前需要做一些回收前的处理,比如看看是否可以让对象重新被引用,Java的Object类
中提供了finalize()
方法来实现这种回收前的处理操作。
finalize()
方法必须被重写才可以使用,在那个类中重写,那个类的实例化对象在被回收之前就会自动的执行该类重写的finalize()
方法,做一些回收前的处理。只要类中重写了finalize()
方法,程序在执行gc()方法进行垃圾回收的时候,程序就会知道在垃圾回收之前,那些类的对象需要进行一些回收前的处理。finalize()方法不需要显示的调用,系统会自动的调用。
但是不建议使用finalize()。因为finalize()方法是在gc()方法执行时才会被执行,但是gc()方法的执行时间是不确定的,所以finalize()方法的调用时机也是不确定的,可能出现的情况是在资源被耗尽之后,gc()方法却仍未执行,这样finalize()方法也不会被调用执行。通常的做法是提供显示的close()方法,进行手动调用。
finalize()示例:
public class Finalize_Book {
public Finalize_Book(){
System.out.println("Book的构造方法");
}
//finalize方法必须被重写才可以调用,在那个类中重写,哪个类的实例化对象才可以调用,在本类的实例化对象被回收之前做一些处理
@Override
protected void finalize() throws Throwable {
System.out.println("可以销毁了!");
}
}
public class Finalize_Test {
public static void main(String[] args) {
//实例化对象
Finalize_Book book = new Finalize_Book();
//把引用指向null,断开了堆内存的指向,表示上面实例已经没有被引用,变成了一个内存垃圾
book = null;
//调用系统的垃圾回收
//如果不手动调用gc()方法进行垃圾回收,那么就要等待程序自动的垃圾回收,系统垃圾回收的时间是不可控的。
System.gc();
}
}
clone克隆
clone()方法是Object类中定义的一个方法,protected修饰。
要得到一个对象,1、可以使用new操作符创建一个对象 。 2、可以通过clone克隆一个对象。clone顾名思义就是复制对象,首先要在堆内存中分配一个和源对象同样大小的内存空间,在这个内存空间中创建一个新的对象,新的对象和源对象的值一致。两个对象之间是完全隔离的,是两个相互独立的实例化对象,在堆内存中拥有单独的内存空间。
使用方法:
-
自定义类,实现Cloneable接口,这个接口没有任何的抽象方法,只是用来标识实现类可以进行克隆。
-
在实现类中自定义一个clone()方法,在clone()方法中通过super.clone(),调用Object类的实现的clone()
Object类中的clone()方法实现的克隆只是一种 “浅克隆”,只会克隆源对象的成员变量和类变量的值,如果源对象中的成员变量是引用类型,那么不会对引用类型的成员变量所指向的对象进行克隆,但是会把引用类型的成员变量的引用克隆,也就是只会把引用的地址值克隆下来。
示例代码:
public class Address {
String detail;
public Address(String detail){
this.detail = detail;
}
@Override
public String toString() {
return "Address{" +
"detail='" + detail + '\'' +
'}';
}
}
public class User implements Cloneable{
static int sex = 1;
static String name = "嘻嘻嘻";
int age;
Address address;
public User(int age){
this.age = age;
this.address = new Address("广州天河");
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "User{" +
"age=" + age +
", address=" + address +
'}';
}
}
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
User user = new User(22);
System.out.println(user);
User user1 = (User) user.clone();
System.out.println(user1);
System.out.println(user == user1);
System.out.println(user.age == user1.age);
System.out.println(user.address == user1.address);
System.out.println(user.sex == user1.sex);
System.out.println(user.name == user1.name);
}
}
Math类
Java提供的一个数学计算的程序功能类,通过这个类,可以非常方便的执行一些基础的数学计算,例如对数、三角函数等。
Math类是一个工具类,它的构造方法是private的,所以无法创建Math类的实例化对象。Math类中的方法都是被static修饰的静态方法。
Math类的常用方法:
方法声明 | |
---|---|
Math.floor(double num) | 取整,返回小于参数的最大整数,返回的结果是double类型 |
Math.ceil(double num) | 取整,返回大于参数的最小整数 |
Math.sqrt(double num) | 计算参数num的平方根 |
Math.cbrt(double num) | 计算参数num的立方根 |
Math.pow(double num, double x) | 计算参数num的x次方 |
Math.abs(double num) | 计算参数num的绝对值 |
Math.max(double num1, double num2) | 计算两个参数的最大值 |
Math.min(double num1, double num2) | 计算两个参数的最小值 |
Math.random() | 返回一个随机数,大于0.0,小于1.0 |
Math.round(double num) | 四舍五入 |
代码示例:
public class Math_Test {
public static void main(String[] args) {
double floor = Math.floor(2.3);
double ceil = Math.ceil(2.3);
double sqrt = Math.sqrt(2.3);
double cbrt = Math.cbrt(2.3);
double pow = Math.pow(2, 3);
double max = Math.max(2.1, 2.3);
double min = Math.min(2.1, 2.3);
double abs = Math.abs(-3.5);
double random = Math.random();
}
}
Random类
Random类是一个随机数类,在实际的开发中,可以通过这个随机数类,很方便的生成一些临时性的内容,比如验证码。
在使用Random类生成随机数的时候,一般都是通过无参构造方法进行实例化对象的。
常用方法:
方法 | |
---|---|
int nextInt() | 得到一个int类型取值范围内的值 |
int nextInt(int found) | 得到一个0到found之间的int类型随机数 |
double nextDouble() | 得到一个0.0~1.0之间的double 类型随机数 |
float nextFloat() | 得到一个0.0~1.0之间的float 类型随机数 |
long nextLong() | 得到一个long类型取值范围内的值 |
boolean nextBoolean() | 随机得到true或false |
示例代码:
public class Random_Test {
public static void main(String[] args) {
Random random = new Random();
System.out.println(random.nextInt());
System.out.println(random.nextInt(20));
System.out.println(random.nextDouble());
System.out.println(random.nextFloat());
System.out.println(random.nextLong());
System.out.println(random.nextBoolean());
}
}
BigInteger类
BigDecimal类是一个Java提供的大数字处理类中的一个,BigInteger支持任意精度的整数,在运算中可以准确地表示任何大小的整数值,而不会丢失任何信息。
BigInteger 类的构造方法只能接收String类型的参数,没有其他的构造方法。
BigInteger只可以处理整数类型。
常用方法:
方法 | |
---|---|
BigInteger add(BigInteger val) | 加法 |
BigInteger subtract(BigInteger val) | 减法 |
BigInteger multiply(BigInteger val) | 乘法 |
BigInteger divide(BigInteger val) | 除法 |
BigInteger remainder(BigInteger val) | 取余 |
XXX xxxValue() | 返回一个把BigInteger 类对象转为xxx基本类型的值 |
int compareTo(BigInteger val) | 比较两个大数字的大小 |
BigInteger示例代码:
public class BigDecimal_String {
public static void main(String[] args) {
//创建一个值为1的BigInteger对象
BigInteger bigInteger = new BigInteger("1");
//创建一个值为2的BigInteger对象
BigInteger bigInteger1 = new BigInteger("2");
BigInteger add = bigInteger.add(bigInteger1);
BigInteger subtract = bigInteger.subtract(bigInteger1);
BigInteger multiply = bigInteger.multiply(bigInteger1);
BigInteger divide = bigInteger.divide(bigInteger1);
int i = bigInteger.intValue();
}
}
BigDecimal类
BigDecimal类是一个Java提供的大数字处理类中的一个,float和double类型有可能会出现精度缺失,在程序中可能会出现超过double类型的取值范围的数据,为了精确的表示计算浮点数,那么就需要用到BigDecimal类来进行处理。
BigDecimal类提供了大量的重载构造方法,通过不同的形参的构造方法,传入不同基本类型的数值,创建对应的BigDecimal类的实例化对象,就可以把所有的基本数值类型转换成BigDecimal对象。像int、float、double、String等都可以。
在创建BigDecimal类的实例化对象的时候,优先建议使用基于String类型参数的构造方法,因为通过String类型参数的构造方法得到的BigDecimal类对象是可预知的。
如果是由double类型参数的构造方法,创建的BigDecimal对象是不可预知的,因为结果只是一个近似值。
常用方法:
方法 | |
---|---|
BigDecimal add(BigDecimal val) | 加法 |
BigDecimal muliiply(BigDecimal val) | 乘法 |
BigDecimal subtract(BigDecimal val) | 减法 |
BigDecimal divide(BigDecimal val) | 除法 |
BigDecimal divide(BigDecimal val, int scale, int roundingMode) | 除法,第二个参数表示小数位,第三个参数表示舍入模式 |
BigDecimal remainder(BigDecimal val) | 取余 |
XXX xxxValue() | 返回一个把BigDecimal类对象转为xxx基本类型的值 |
int compareTo(BigDecimal val) | 比较两个大数字的大小 |
String类型参数的示例代码:
public class BigDecimal_String {
public static void main(String[] args) {
//通过String类型参数的构造方法,创建一个BigDecimal对象,值为0.1
BigDecimal decimal = new BigDecimal("0.1");
//通过String类型参数的构造方法,创建一个BigDecimal对象,值为0.05
BigDecimal decimal1 = new BigDecimal("0.05");
BigDecimal add = decimal.add(decimal1);
BigDecimal multiply = decimal.multiply(decimal1);
BigDecimal divide = decimal.divide(decimal1);
BigDecimal subtract = decimal.subtract(decimal1);
}
}
double类型参数的示例代码:
public class BigDecimal_String {
public static void main(String[] args) {
//通过double类型参数的构造方法,创建一个BigDecimal对象,值为0.1
BigDecimal decimal = new BigDecimal(0.1);
//通过double类型参数的构造方法,创建一个BigDecimal对象,值为0.05
BigDecimal decimal1 = new BigDecimal(0.05);
BigDecimal add = decimal.add(decimal1);
BigDecimal multiply = decimal.multiply(decimal1);
BigDecimal divide = decimal.divide(decimal1);
BigDecimal subtract = decimal.subtract(decimal1);
}
}
BigInteger和BigDecimal总结:
-
相同点:
-
BigInteger类和BigDecimal类都是Java提供的用来处理范围很大的数据的类。
-
BigInteger类和BigDecimal类的用法基本相似,类中的方法也都大致相同。
-
BigInteger与BigDecimal都是不可变的,在进行每一步运算时,都会产生一个新的对象
-
-
不同点:
-
BigInteger类只可以处理整数类型,而BigDecimal类可以处理整数和小数类型。
-
BigInteger类的divide()进行除法运算,会四舍五入,舍弃掉小数,BigDecimal类的除法运算不会。
-
Base64加密与解密
Base64是程序开发过程中比较常见的一种加密与解密的处理方式,是在JDK1.8之后才开始提供的工具类。
在程序开发中,为了数据的安全,一般都会对数据进行加密,一旦加密之后,就需要通过特定的方式进行解密才能得到数据。
Base 64主要用途不是加密,而是把一些二进制数转成普通字符,方便在网络上传输,Base64特别适合在http,mime协议下快速传输数据。比如网络中图片的传输。
Base64,并非安全领域下的加密解密算法,Base64只能算是一个编码算法,对数据内容进行编码来适合传输。
Base64编码过后的原文变成不能看到的字符格式,使用方式比较简单。
Encoder和Decoder分别是Base64类中的两个静态内部类,一个加密,一个解密。通过Base64.getEncoder()
和Base64.getDecoder()
来获取对象进行加密解密操作,加密和解密方法只可以对字节数据进行加密解密。
示例代码:
public class Base64_Test {
public static void main(String[] args) {
String str = "需要加密的内容";
//获取Base64类的内部加密工具类对象
Base64.Encoder encoder = Base64.getEncoder();
//进行加密,返回字节数组
byte[] encode = encoder.encode(str.getBytes());
//加密,并且把byte[]转换为String类型并返回
String s = encoder.encodeToString(str.getBytes());
System.out.println(new String(encode));
//获取解密工具类对象
Base64.Decoder decoder = Base64.getDecoder();
//进行解密,返回字节数组
byte[] decode = decoder.decode(encode);
System.out.println(new String(decode));
}
}
多次加密和解密案例:
//加密解密工具类
public class Base64_Utils {
private static final int REPEAT = 5;//循环次数
private static final String SALT = "yjz"; //追加操作盐值
//因为不希望通过对象去调用,所以把构造方法设置为private,这样就无法创建对象,
//并且把方法都定义为静态方法,这样就只可以通过类进行调用。
private Base64_Utils(){}
//加密方法
public static String encrpy(String message){
//把需要加密的数据和盐值合并,提高加密的安全性
String encodeData = SALT + message;
//获得加密的工具类对象
Base64.Encoder encoder = Base64.getEncoder();
//循环多次加密
for (int i=0; i<REPEAT; i++){
encodeData = encoder.encodeToString(encodeData.getBytes());
}
return encodeData;
}
//解密方法
public static String decrpy(String message){
//获得解密的工具类对象
Base64.Decoder decoder = Base64.getDecoder();
byte[] decodeData = message.getBytes();
//加密多少次,就需要解密多少次
for (int i = 0; i<REPEAT; i++){
//进行解密
decodeData = decoder.decode(decodeData);
}
String data = new String(decodeData);
//把加密时加的盐值减掉。
return data.substring(SALT.length());
}
}
UUID
UUID属于一种生成算法,主要功能就是生成生成一个不会重复的数据,原理是通过时间的不重复来计算的。UUID是基于时间的一种数据工具类。
在开发中,需要程序自动生成不会重复的数据时,最佳的做法就是使用UUID进行处理。
通过UUID类的静态方法randomUUID()获取到一个uuid值。
示例代码:
public class UUID_Test {
public static void main(String[] args) {
//获取一个uuid
UUID uuid = UUID.randomUUID();
System.out.println(uuid);
//把UUID对象转为String类型
String str = uuid.toString();
System.out.println(str);
}
}
Optional类
在引用数据类型的处理过程中,如果处理不当,就有可能会出现空指针异常
。
Optional类是JDK1.8
后提供的一个系统类,这个类可以保证存储的数据不为null
。
常用方法:
方法 | |
---|---|
Optional.of(T value) | 返回一个Optional对象,value不可以为空 |
Optional.ofNullable(T value) | 返回一个Optional对象,value可以为空 |
Optional.empty() | 返回一个空的Optional对象 |
boolean isPresent() | 判断Optional是否存在有内容 |
T get() | 从Optional中取出对应的数据 |
T orElse(T value) | 当Optional对象有值则返回该值,否则返回传递给它的参数值 |
T orElseGet(Supplier<?extends T> other) | 当Optional对象有值则返回该值,否则它会执行作为参数传入的 Supplier(供应者) 函数式接口,并将返回其执行结果,其实就是调用的Optional类的get()方法 |
示例代码:
public class Optional_Test {
public static void main(String[] args) {
//返回一个value不能为空的Optional对象
Optional<String> optional = Optional.of("hello");
//返回一个value可以为空的Optional对象
Optional<String> optional1 = Optional.ofNullable(null);
//返回一个空的Optional对象
Optional<String> optional2 = Optional.empty();
//判断Optional对象是否存在内容
boolean present = optional.isPresent();
//true
System.out.println("Optional.of()创建的是否存在内容:"+present);
//判断Optional对象是否存在内容
boolean present1 = optional1.isPresent();
//false
System.out.println("Optional.ofNullable()创建的是否存在内容:"+present1);
//判断Optional对象是否存在内容
boolean present2 = optional2.isPresent();
//false
System.out.println("Optional.empty()创建的是否存在内容:"+present2);
//从Optional中取出对应的数据
String s = optional.get();
//报异常,因为optional1的内容为空
String s1 = optional1.get();
//报异常,因为optional2的内容为空
String s2 = optional2.get();
//当Optional对象有值则返回该值,否则返回传递给它的参数值
String opt = optional.orElse("optional");
//输出hello
System.out.println("Optional.of():"+opt);
String opt1 = optional1.orElse("optional");
//输出optional
System.out.println("Optional.ofNullable():"+opt1);
String opt2 = optional2.orElse("optional");
//输出optional
System.out.println("Optional.empty():"+opt2);
}
}
比较器
在Java开发中,比较器是一种比较常见的功能,在整个Java中,比较器都是有着很重要的地位。
如果想比较两个引用类型对象实例的大小,就必须首先比较器接口。但是两个比较的对象必须是同一类型。
在Java中支持两种比较器:Comparable、 Comparator
Comparable
对象实现Comparable接口,重写compareTo()方法。
接口后面的泛型类型是比较器可以比较的对象的类型,用来确定两个比较大小的对象是同一类型的。
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Student o) {
if (this.age > o.age){
return 1;
}else if (this.age < o.age){
return -1;
}
return 0;
}
}
public class Test {
public static void main(String[] args) {
Student s1 = new Student("xxx",22);
Student s2 = new Student("yyy",23);
int i = s1.compareTo(s2);
System.out.println(i);
}
}
Comparator
comparator接口相当于是一种补救,在无法修改类的情况下,就可以使用这个接口,需要自定义一个比较器类并实现Comparator接口,然后重写compare(Object o1, Object o2)方法。在通过这个比较器类的实例化对象对两个相同类型的对象进行比较。
//没有实现任何接口,就是一个普通的类
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
//比较器类
public class PersonComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
if (o1.getAge() > o2.getAge()){
return 1;
}else if (o1.getAge() < o2.getAge()){
return -1;
}
return 0;
}
}
//测试类
public class Test {
public static void main(String[] args) {
Person p1 = new Person("xxx",22);
Person p2 = new Person("yyy",23);
PersonComparator comparator = new PersonComparator();
int i = comparator.compare(p1, p2);
System.out.println(i);
}
}
String类
String类是不可变类,每一次的操作都会产生新的字符串。
方法 | |
---|---|
int length() | 返回字符串长度 |
char charAt(int i) | 根据下标获取字符 |
boolean contains(String str) | 判断是否包含str |
char[] toCharArray() | 将字符串转为字符数组 |
int indexOf(String str) | 返回str首次出现的下标,不存在返回-1 |
int indexOf(String str,int fromIndex) | 返回从fromIndex开始的str首次出现的下标,不存在返回-1 |
int lastIndexOf(String str) | 返回str最后一次出现的下标,不存在返回-1 |
int lastIndexOf(String str,int fromIndex) | 返回从fromIndex开始的str最后一次出现的下标,不存在返回-1 |
String trim() | 去掉字符串前后的空格,中间的无法去掉 |
String toUpperCase() | 将小写转为大写 |
String toLowerCase() | 将大写转为小写 |
boolean endWith(String str) | 判断字符串是否以str结尾 |
boolean startsWith(String str) | 判断字符串是否以str开头 |
String replace(char oldChar,char newChar) | 返回新用newChar替换掉oldChar后的字符串 |
String[] split(String str) | 根据str进行拆分 |
String subString(int beginIndex) | 从beginIndex开始往后面截取字符串 |
String subString(int beginIndex,int endIndex) | 截取beginIndex到endIndex的字符串 |
案例:
public class StringTest {
public static void main(String[] args) {
String str = "I Like JAVA";
System.out.println(str.length());
System.out.println(str.charAt(2));
System.out.println(str.contains("Like"));
System.out.println(str.toCharArray());
System.out.println(str.indexOf("A"));
System.out.println(str.indexOf("A", 9));
System.out.println(str.lastIndexOf("A"));
System.out.println(str.lastIndexOf("A", 9));
System.out.println(str.trim());
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());
System.out.println(str.endsWith("A"));
System.out.println(str.startsWith("I"));
str = str.replace("Like","Very Like");
System.out.println(str);
String[] arr = str.split(" ");
for (String s : arr) {
System.out.println(s);
}
System.out.println(str.substring(3));
System.out.println(str.substring(3,8));
}
}
StringBuffer、StringBuilder
StringBuffer:可变长字符串,效率比较低,线程安全。
StringBuilder:可变长字符串,效率比较高,线程不安全。
效率都比String高,比String节省内存空间。
方法 | |
---|---|
StringBuffer append(String str) | 追加字符串str |
StringBuffer insert(int offset,String str) | 在offset位置插入str |
StringBuffer replace(int start,int end,String str) | 用str替换掉 原字符串start到end的内容 |
StringBuffer delete(int start,int end) | 删除start到end的内容 |
案例:
public class StringBTest {
public static void main(String[] args) {
StringBuffer sb1 = new StringBuffer("hello");
StringBuffer sb2 = sb1.append("java");
System.out.println(sb1);
System.out.println(sb2);
//指向的是同一个对象
System.out.println(sb1 == sb2);//true
StringBuffer xxx = sb1.replace(0, 2, "xxx");
System.out.println(xxx);
System.out.println(sb1 == xxx);//true
System.out.println(sb1.delete(0,2));
System.out.println(sb1.insert(1,"sss"));
}
}