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();//10000System.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); //2022System.out.println(month); //9//给日期时间的年份加3calendar.add(Calendar.YEAR,3);//获得加3年后的年份int year2 = calendar.get(Calendar.YEAR);System.out.println(year2);//2025//给日期时间的月份加2calendar.add(Calendar.MONTH,2);//获得加2个月后的月份int month2 = calendar.get(Calendar.MONTH); System.out.println(month2); //11//设置日期时间的年份的值为1999calendar.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 2000System.out.println(year4); //2000System.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.FULLDateFormat.LONGDateFormat.MEDIUMDateFormat.SHORT四种静态常量。

还可以通过传入时区静态常量locale,指定时区,Locale.CHINALocale.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");}@Overridepublic 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");}@Overridepublic 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方法必须被重写才可以调用,在那个类中重写,哪个类的实例化对象才可以调用,在本类的实例化对象被回收之前做一些处理@Overrideprotected 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顾名思义就是复制对象,首先要在堆内存中分配一个和源对象同样大小的内存空间,在这个内存空间中创建一个新的对象,新的对象和源对象的值一致。两个对象之间是完全隔离的,是两个相互独立的实例化对象,在堆内存中拥有单独的内存空间。

使用方法:

  1. 自定义类,实现Cloneable接口,这个接口没有任何的抽象方法,只是用来标识实现类可以进行克隆。

  2. 在实现类中自定义一个clone()方法,在clone()方法中通过super.clone(),调用Object类的实现的clone()

Object类中的clone()方法实现的克隆只是一种 “浅克隆”,只会克隆源对象的成员变量和类变量的值,如果源对象中的成员变量是引用类型,那么不会对引用类型的成员变量所指向的对象进行克隆,但是会把引用类型的成员变量的引用克隆,也就是只会把引用的地址值克隆下来。

示例代码:

public class Address {String detail;public Address(String detail){this.detail = detail;}
​@Overridepublic 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("广州天河");}
​@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}
​@Overridepublic 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.1BigDecimal decimal = new BigDecimal("0.1");//通过String类型参数的构造方法,创建一个BigDecimal对象,值为0.05BigDecimal 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.1BigDecimal decimal = new BigDecimal(0.1);//通过double类型参数的构造方法,创建一个BigDecimal对象,值为0.05BigDecimal 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) {//获取一个uuidUUID 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();//trueSystem.out.println("Optional.of()创建的是否存在内容:"+present);//判断Optional对象是否存在内容boolean present1 = optional1.isPresent();//falseSystem.out.println("Optional.ofNullable()创建的是否存在内容:"+present1);//判断Optional对象是否存在内容boolean present2 = optional2.isPresent();//falseSystem.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");//输出helloSystem.out.println("Optional.of():"+opt);String opt1 = optional1.orElse("optional");//输出optionalSystem.out.println("Optional.ofNullable():"+opt1);String opt2 = optional2.orElse("optional");//输出optionalSystem.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;}
​@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}
​@Overridepublic 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;}
​@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}
}
//比较器类
public class PersonComparator implements Comparator<Person> {
​@Overridepublic 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);//trueStringBuffer xxx = sb1.replace(0, 2, "xxx");System.out.println(xxx);System.out.println(sb1 == xxx);//trueSystem.out.println(sb1.delete(0,2));System.out.println(sb1.insert(1,"sss"));}
}

Java常用类学习笔记相关推荐

  1. Java字符串类学习笔记

    String String特性 String:字符串,使用一对""引起来表示. String声明为final的,不可被继承 String实现了Serializable接口:表示字符 ...

  2. 【java】java学习笔记之java常用类

    如下图所示为笔者总结的java常用类学习笔记,其中,附带有代码示例(未展开),方便理解记忆.需要源文件的请到我的资源中下载,下载地址:https://download.csdn.net/downloa ...

  3. Java快速入门学习笔记7 | Java语言中的类与对象

    有人相爱,有人夜里开车看海,有人却连LeetCode第一题都解不出来!虽然之前系统地学习过java课程,但是到现在一年多没有碰过Java的代码,遇到LeetCode不知是喜是悲,思来想去,然后清空自己 ...

  4. Java常用类(谷粒商城学习记录)

    Java常用类 谷粒商城学习记录 谷粒商城学习记录 谷粒商城学习记录 干嘛老是提示我与别人的文章相似呢?真的是我自己整理的啊啊啊 老是提示与这个文章相似 https://blog.csdn.net/c ...

  5. 第八章笔记 Java常用类

    第八章笔记 Java常用类 文章目录 第八章笔记 Java常用类 第一节 Java类库概述 Java类库文档 Java类库列表 第二节 数字相关类 Java数字类 大数字类 随机数类 数字工具类 第三 ...

  6. 学习-Java常用类之Calendar类

    第1关:学习-Java常用类之Calendar类 任务描述 本关任务:获取给定年月的最后一天. 相关知识 我们通过之前的学习已经能够格式化并创建一个日期对象了,但是我们如何才能设置和获取日期数据的特定 ...

  7. java笔记——Java常用类

    目录 目录 Java常用类目标 1.1内部类 1.2成员内部类 1.3静态内部类 1.4匿名内部类 2.Object类 2.1getClass()方法 2.2hasCode() 2.3toString ...

  8. Java基础篇 学习笔记

    List item Java基础篇 学习笔记 java基础篇 第1章 计算机.程序和java概述 学习笔记 1.1什么是计算机 简单来说:计算机就是 ' 存储 ' 和 ' 处理 ' 数据的电子设备. ...

  9. Java微服务学习笔记(一):微服务架构的概念理解

    Java微服务学习笔记 Tips:入门学习时粗略整理,仅供参考 (一):架构的基础理解 文章目录 Java微服务学习笔记 前言 一.微服务是什么? 二.常用开源微服务框架演化 1. Dubbo 2. ...

最新文章

  1. Kubernetes入门
  2. ubuntu服务器版编辑文件,Ubuntu 服务器版 18.04.4 固定 IP 设置
  3. pandas使用bdate_range函数获取起始时间(start)和结束时间(end)范围内的所有周末日期(weekends day)
  4. 数据结构(算法)-线性表2(单链表)
  5. weblogic与sitemesh乱码问题
  6. http://blog.chinaunix.net/uid-20577907-id-3519578.html
  7. 什么是IP地址、子网掩码、路由和网关?
  8. c语言用switch字母判断星期几,c语言程序,输入年月日,判断这一天是这一年的第几天,同时判断这一天是星期几。(用switch语句)...
  9. 己所不欲,勿施于人的意思,这句话出自哪里?
  10. 使用HslCommunication实现PLC数据的远程客户端监视,以及web端实时监视,远程操作设备示例...
  11. Smarty中直接加JS代码和将JS代码写在literal标签里
  12. using的基本用法
  13. 大数据开发离线计算框架知识点总结
  14. 第二届广东省大学生网络攻防大赛 pyre
  15. 电阻转换温度值c语言,PT1000电阻值转化为温度值的计算公式
  16. 国际电离层参考模型程序说明
  17. qq离线linux,QQ For Linux 我哭了,官方版
  18. HDMI转Displayport转换器支持4K分辨率
  19. 为任意屏幕尺寸构建 Android 界面
  20. 正大国际:你所应该知道的外盘国际期货知识

热门文章

  1. JAVA随机生成6位数,不足补0
  2. github上提交pr的完整流程
  3. IOS开发高手课第三篇 App Auto Layout 是怎么进行自动布局的,性能如何?
  4. mysql 入库乱码,如何解决mysql中文入库乱码问题
  5. 【Proteus仿真】74HC165功能验证
  6. GateWay的介绍与使用
  7. android视频gif编辑器,GIF制作编辑
  8. 【案例9】sysConfig 中文乱码(方块)
  9. 转:数据可视化之美:经典案例与实践解析
  10. 1029: 三角形判定 Python