Java常用类

包装类

包装类定义

包装类就是将基本数据类型封装到类中,使基本数据类型具有类的特点,方便操作

包装类分类

  • byte -> Byte
  • short -> Short
  • int -> Integer
  • long -> Long
  • float -> Float
  • double -> Double
  • char -> Character
  • boolean -> Boolean

基本数据类型与包装类之间的转换

在JDK5之前,基本数据类型与包装类之间的转换需要手动编写代码实现,在JDK5之后,Java提供了自动装箱和自动拆箱功能,使基本数据类型与包装类之间的转换更加方便。

在JDK5之前,基本数据类型与包装类之间的转换需要手动编写代码实现,例如:

基本数据类型转换为包装类
  • 调用包装类的构造方法
  • 调用包装类的静态方法valueOf
Integer i = new Integer(10); // 调用构造方法
Integer j = Integer.valueOf(10); // 调用静态方法
包装类转换为基本数据类型
  • 调用包装类的xxxValue方法
int k = i.intValue(); // 调用intValue方法
int l = j.intValue(); // 调用intValue方法

在JDK5之后,Java提供了自动装箱和自动拆箱功能,使基本数据类型与包装类之间的转换更加方便。

基本数据类型转换为包装类
  • 自动装箱
Integer m = 10; // 自动装箱
包装类转换为基本数据类型
  • 自动拆箱
int n = m; // 自动拆箱

包装类和String之间的转换

包装类转换为String

  • 调用包装类的toString方法
  • 调用String类的valueOf方法
Integer i = 10;
String str1 = i.toString(); // 调用toString方法
String str2 = String.valueOf(i); // 调用valueOf方法

String转换为包装类

  • 调用包装类的parseXxx方法
String str = "10";
Integer i = Integer.parseInt(str); // 调用parseInt方法
Double d = Double.parseDouble(str); // 调用parseDouble方法

包装类常用方法

  • Integer类
    • Integer.parseInt(String s) 将字符串转换为int类型
    • Integer.valueOf(String s) 将字符串转换为Integer类型
    • Integer.toString(int i) 将int类型转换为字符串
    • Integer.toBinaryString(int i) 将int类型转换为二进制字符串
    • Integer.toHexString(int i) 将int类型转换为十六进制字符串
    • Integer.toOctalString(int i) 将int类型转换为八进制字符串
  • Character类
    • Character.isDigit(char ch) 判断字符是否为数字
    • Character.isLetter(char ch) 判断字符是否为字母
    • Character.isUpperCase(char ch) 判断字符是否为大写字母
    • Character.isLowerCase(char ch) 判断字符是否为小写字母
    • Character.toUpperCase(char ch) 将字符转换为大写字母

Integer类比较的注意点

Integer类在比较时,会先比较对象的地址,如果地址相同,则返回true,如果地址不同,则比较对象的值,如果值相同,则返回true,否则返回false。
当Integer的值在-128到127之间时,Integer对象是在IntegerCache.cache产生,会复用已有对象,所以比较时为true,超出这个范围时,会重新在堆上创建对象,所以比较时为false。

//这里比较的是对象的地址,创建了两个不同的对象,所以比较时为false
Integer i1 = new Integer(127);
Integer i2 = new Integer(127);
System.out.println(i1 == i2); // false

//这里比较的两个对象均由cache产生,所以比较时为true
Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1 == i2); // true

//这里比较的是对象的地址,创建了两个不同的对象,所以比较时为false
Integer i3 = 128;
Integer i4 = 128;
System.out.println(i3 == i4); // false

而当和基础类型比较时,则比较的是值

Integer i1 = 127;
int i2 = 127;
System.out.println(i1 == i2); // true

Integer i3 = 128;
int i4 = 128;
System.out.println(i3 == i4); // true

String类

String对象用于保存字符串,也就是一组字符序列;字符串的字符用的是unicode编码,一个字符两个字节,一个汉字也是两个字节。
String实现了Serializable接口,表示字符串是支持序列化的;实现了Comparable接口,表示String对象可以比较大小。
String内部定义了final char[] value用于保存字符串,所以String对象是不可变的。

String的创建

String的创建有两种方式:

  1. 直接赋值
String s1 = "hello";
String s2 = "hello"; //s1和s2指向同一个常量池中的对象
  1. 使用new关键字
String s1 = new String("hello");
String s2 = new String("hello"); //s1,s2分别指向堆中的两个不同的对象,然后这两个堆中的对象都指向常量池中的同一个对象

String的不可变性

String的不可变性体现在:

  1. String类被final修饰,不能被继承
  2. String内部定义的char[]被final修饰,不能被改变
  3. String内部定义的char[]被private修饰,只能通过get方法获取

String的常用方法

  1. int length():返回字符串的长度
  2. char charAt(int index):返回指定索引处的字符
  3. boolean isEmpty():判断字符串是否为空
  4. String toLowerCase():将字符串转换为小写
  5. String toUpperCase():将字符串转换为大写
  6. String trim():去除字符串两端的空格
  7. boolean equals(Object obj):比较字符串的内容是否相同
  8. boolean equalsIgnoreCase(String anotherString):比较字符串的内容是否相同,忽略大小写
  9. String concat(String str):将指定字符串连接到此字符串的末尾
  10. int indexOf(String str):返回指定子字符串在此字符串中第一次出现的索引
  11. int lastIndexOf(String str):返回指定子字符串在此字符串中最后一次出现的索引
  12. String substring(int beginIndex):返回一个新的字符串,它是此字符串的一个子字符串
  13. String substring(int beginIndex, int endIndex):返回一个新的字符串,它是此字符串的一个子字符串

StringBuffer类

StringBuffer是一个可变的字符序列,可以对字符串进行增删改查操作。StringBuffer是线程安全的,内部使用synchronized关键字保证线程安全。

StringBuffer和String之间的区别

String保存的是字符串常量,StringBuffer保存的是字符串变量。String是不可变的,每次对String进行操作都会创建一个新的String对象,而StringBuffer是可变的,每次对StringBuffer进行操作都是在原来的基础上进行修改,效率较高。

StringBuffer的创建

StringBuffer的创建有两种方式:

  1. 直接赋值
StringBuffer sb1 = new StringBuffer("hello");
StringBuffer sb2 = new StringBuffer("hello"); //sb1和sb2指向同一个StringBuffer对象
  1. 使用new关键字
StringBuffer sb1 = new StringBuffer();
StringBuffer sb2 = new StringBuffer(10); //指定容量为10的StringBuffer对象

StringBuffer和String之间的转换

  1. StringBuffer转String
StringBuffer sb = new StringBuffer("hello");
String str = sb.toString();
  1. String转StringBuffer
String str = "hello";
StringBuffer sb = new StringBuffer(str);

StringBuffer的常用方法

  1. append(String str):在字符串末尾追加指定的字符串
  2. insert(int offset, String str):在指定位置插入指定的字符串
  3. delete(int start, int end):删除指定位置的字符序列
  4. replace(int start, int end, String str):替换指定位置的字符序列
  5. reverse():将字符串反转
  6. length():返回字符串的长度

StringBuilder

StringBuilder是StringBuffer的简化版,它不是线程安全的,但效率更高。StringBuilder的方法和StringBuffer的方法基本相同,只是没有synchronized关键字保证线程安全。

StringBuilder的创建

StringBuilder的创建有两种方式:

  1. 直接赋值
StringBuilder sb1 = new StringBuilder("hello");
StringBuilder sb2 = new StringBuilder("hello"); //sb1和sb2指向同一个StringBuilder对象
  1. 使用new关键字
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder(10); //指定容量为10的StringBuilder对象

StringBuilder和String之间的转换

  1. StringBuilder转String
StringBuilder sb = new StringBuilder("hello");
String str = sb.toString();
  1. String转StringBuilder
String str = "hello";
StringBuilder sb = new StringBuilder(str);

Math类

Math类是java.lang包下的一个类,它提供了一些数学运算的方法,如求绝对值、取整、求平方根等,这些方法都是静态方法,可以直接通过类名调用。

Math类的常用方法

  1. abs(double a):返回a的绝对值
double a = -10.5;
double b = Math.abs(a);
System.out.println(b); // 输出10.5
  1. ceil(double a):返回大于等于a的最小整数
double a = 10.5;
double b = Math.ceil(a);
System.out.println(b); // 输出11.0
  1. floor(double a):返回小于等于a的最大整数
double a = 10.5;
double b = Math.floor(a);
System.out.println(b); // 输出10.0
  1. round(double a):返回最接近a的整数
double a = 10.5;
double b = Math.round(a);
System.out.println(b); // 输出11.0
  1. sqrt(double a):返回a的平方根
double a = 16;
double b = Math.sqrt(a);
System.out.println(b); // 输出4.0
  1. pow(double a, double b):返回a的b次方
double a = 2;
double b = Math.pow(a, 3);
System.out.println(b); // 输出8.0
  1. random():返回一个0.0到1.0之间的随机数
double a = Math.random();
System.out.println(a); // 输出一个随机数
  1. max(double a, double b):返回a和b中的较大值
double a = 10;
double b = 20;
double c = Math.max(a, b);
System.out.println(c); // 输出20.0
  1. min(double a, double b):返回a和b中的较小值
double a = 10;
double b = 20;
double c = Math.min(a, b);
System.out.println(c); // 输出10.0

Arrays类

Arrays类是Java中的一个实用工具类,用于操作数组。它提供了一些静态方法,可以方便地对数组进行排序、搜索、填充等操作。

  1. sort(T[] a):对数组a进行排序
int[] a = {5, 2, 8, 1, 9};
Arrays.sort(a);
System.out.println(Arrays.toString(a)); // 输出[1, 2, 5, 8, 9]
  1. binarySearch(T[] a, T key):在数组a中查找元素key,返回其索引。如果未找到,则返回负数
int[] a = {1, 2, 3, 4, 5};
int index = Arrays.binarySearch(a, 3);
System.out.println(index); // 输出2
  1. fill(T[] a, T val):将数组a中的所有元素填充为val
int[] a = new int[5];
Arrays.fill(a, 10); // 将数组a中的所有元素填充为10
System.out.println(Arrays.toString(a)); // 输出[10, 10, 10, 10, 10]
  1. toString(T[] a):将数组a转换为字符串形式
int[] a = {1, 2, 3, 4, 5};
String str = Arrays.toString(a);
System.out.println(str); // 输出[1, 2, 3, 4, 5]
  1. equals(T[] a, T[] b):比较两个数组a和b是否相等
int[] a = {1, 2, 3, 4, 5};
int[] b = {1, 2, 3, 4, 5};
boolean isEqual = Arrays.equals(a, b);
System.out.println(isEqual); // 输出true
  1. asList(T… a):将数组a转换为List形式
int[] a = {1, 2, 3, 4, 5};
List<Integer> list = Arrays.asList(a);
System.out.println(list); // 输出[1, 2, 3, 4, 5]
  1. copyOf(T[] original, int newLength):复制数组original,生成一个新的数组,长度为newLength
int[] a = {1, 2, 3, 4, 5};
int[] b = Arrays.copyOf(a, 10);
System.out.println(Arrays.toString(b)); // 输出[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]

System类

  1. exit(int status):终止当前运行的Java虚拟机,非零表示异常终止
System.exit(0); // 正常终止
System.exit(1); // 异常终止
  1. gc():运行垃圾回收器
System.gc();
  1. currentTimeMillis():返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差
long startTime = System.currentTimeMillis();
// 执行一些操作
long endTime = System.currentTimeMillis();
long elapsedTime = endTime - startTime;
System.out.println("操作耗时:" + elapsedTime + "毫秒");
  1. arraycopy(Object src, int srcPos, Object dest, int destPos, int length):复制数组
int[] a = {1, 2, 3, 4, 5};
int[] b = new int[5];
System.arraycopy(a, 0, b, 0, 5);
System.out.println(Arrays.toString(b)); // 输出[1, 2, 3, 4, 5]

BigInteger类 和 BigDecimal类

  1. BigInteger:可存储任意精度的整数
  2. BigDecimal:可存储任意精度的有符号小数
  3. 构造方法:
BigInteger a = new BigInteger("12345678901234567890");//存储一个超级超级大的数
BigDecimal b = new BigDecimal("123.45323123123143242342343246");//存储一个精度超级超级高的数
  1. 常用方法:
BigInteger add(BigInteger val) // 加法
BigInteger subtract(BigInteger val) // 减法
BigInteger multiply(BigInteger val) // 乘法
BigInteger divide(BigInteger val) // 除法
BigInteger remainder(BigInteger val) // 求余
BigInteger[] divideAndRemainder(BigInteger val) // 求商和余数
BigInteger pow(int exponent) // 求幂
BigInteger gcd(BigInteger val) // 求最大公约数
BigInteger abs() // 求绝对值
BigInteger negate() // 求相反数
BigDecimal add(BigDecimal val) // 加法
BigDecimal subtract(BigDecimal val) // 减法
BigDecimal multiply(BigDecimal val) // 乘法
BigDecimal divide(BigDecimal val) // 除法
BigDecimal remainder(BigDecimal val) // 求余
BigDecimal[] divideAndRemainder(BigDecimal val) // 求商和余数
BigDecimal pow(int exponent) // 求幂
BigDecimal abs() // 求绝对值
BigDecimal negate() // 求相反数
BigDecimal round(MathContext mc) // 四舍五入,MathContext mc是精度和舍入模式

Date类

  1. Date类表示一个特定的时间,精确到毫秒
  2. 构造方法:
Date d = new Date();//获取当前时间
Date d = new Date(long time);//获取指定时间,long time为毫秒数
  1. 常用方法:
long getTime();//获取当前时间,返回毫秒数
void setTime(long time);//设置当前时间,long time为毫秒数

输出当前时间:

Date date = new Date();
System.out.println(date);

此处输出的时间格式为:Sat Jan 07 17:22:32 CST 2023,当我们希望将其输出格式转换时,可以使用下属的SimpleDateFormat类

DateFormat类

  1. DateFormat是一个抽象类,不能直接创建对象,需要使用其子类SimpleDateFormat,这个类型的作用是格式化和解析日期

  2. 构造方法:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1. 常用方法:
String format(Date date);//将Date对象格式化为字符串
Date parse(String source);//将字符串解析为Date对象

示例使用:

// 格式化
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = sdf.format(date);
System.out.println(str);

// 解析
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = "2023-01-07 17:22:32"; //注意这里要解析的格式一定要和SimpleDateFormat中的格式一致
Date date2 = sdf.parse(str);
System.out.println(date2);

Calendar类

  1. Calendar是一个抽象类,不能直接创建对象,需要使用其子类GregorianCalendar,这个类型的也可以获取和设置日期时间

  2. 创建方法:

Calendar c = Calendar.getInstance();
  1. 常用方法:
int get(int field);//获取指定字段的值
void set(int field, int value);//设置指定字段的值
void add(int field, int amount);//对指定字段进行加减操作
Date getTime();//将Calendar对象转换为Date对象
void setTime(Date date);//将Date对象转换为Calendar对象

示例使用:

// 获取当前日期时间
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH) + 1; //月份从0开始,需要加1
int day = c.get(Calendar.DAY_OF_MONTH);
int hour = c.get(Calendar.HOUR); //12小时制
//int hour = c.get(Calendar.HOUR_OF_DAY);   //24小时制
int minute = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);

System.out.println(year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second);

第三代日期类

  1. LocalDate:只包含日期,不包含时间,格式为yyyy-MM-dd
  2. LocalTime:只包含时间,不包含日期,格式为HH:mm:ss
  3. LocalDateTime:包含日期和时间,格式为yyyy-MM-dd HH:mm:ss
  4. DateTimeFormatter:日期时间格式化类
  5. Instant:时间戳类,表示一个精确到纳秒的时间点

示例使用:

// 获取当前日期时间
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();

System.out.println(date);
System.out.println(time);
System.out.println(dateTime);

日期时间格式化

日期时间格式化是指将日期时间对象转换为字符串,或者将字符串解析为日期时间对象的过程。Java 8 提供了 DateTimeFormatter 类来处理日期时间格式化。

常用方法:

  • ofPattern(String pattern):根据指定的模式创建日期时间格式化对象
  • format(TemporalAccessor temporal):将日期时间对象格式化为字符串
  • parse(CharSequence text, DateTimeFormatter formatter):将字符串解析为日期时间对象

示例代码:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

// 创建日期时间格式化对象
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

// 将日期时间对象格式化为字符串
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
String dateStr = date.format(formatter);
String timeStr = time.format(formatter);
String dateTimeStr = dateTime.format(formatter);

// 将字符串解析为日期时间对象
String str = "2025-01-22 12:00:00";
LocalDateTime dateTime2 = LocalDateTime.parse(str, formatter);

第三类日期类常用方法:

  1. now():获取当前日期时间
  2. of():根据指定日期时间创建对象
  3. parse():根据指定格式解析字符串为日期时间对象
  4. format():将日期时间对象格式化为字符串
  5. plus():对日期时间进行加减操作
  6. minus():对日期时间进行减操作
  7. isBefore()、isAfter():比较两个日期时间的大小
  8. getYear()、getMonthValue()、getDayOfMonth()、getHour()、getMinute()、getSecond():获取日期时间的年、月、日、时、分、秒等字段值

示例使用:

// 获取当前日期时间
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();

// 根据指定日期时间创建对象
LocalDate date1 = LocalDate.of(2025, 1, 22);
LocalTime time1 = LocalTime.of(12, 0, 0);
LocalDateTime dateTime1 = LocalDateTime.of(2025, 1, 2212, 0, 0);

// 根据指定格式解析字符串为日期时间对象
LocalDate date2 = LocalDate.parse("2025-01-22");
LocalTime time2 = LocalTime.parse("12:00:00");
LocalDateTime dateTime2 = LocalDateTime.parse("2025-01-22 12:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
// 将日期时间对象格式化为字符串
String dateStr = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
String timeStr = time.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
String dateTimeStr = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

// 对日期时间进行加减操作
LocalDate date3 = date.plusDays(1);
LocalTime time3 = time.plusHours(1);
LocalDateTime dateTime3 = dateTime.plusMinutes(1);

// 对日期时间进行减操作
LocalDate date4 = date.minusDays(1);
LocalTime time4 = time.minusHours(1);
LocalDateTime dateTime4 = dateTime.minusMinutes(1);

日期时间比较

日期时间比较是指比较两个日期时间对象的大小关系。Java 8 提供了 Temporal 接口和 TemporalAdjuster 接口来处理日期时间比较。

常用方法:

  • isBefore(Temporal other):判断当前日期时间是否在指定日期时间之前
  • isAfter(Temporal other):判断当前日期时间是否在指定日期时间之后
  • isEqual(Temporal other):判断当前日期时间是否与指定日期时间相等
  • until(Temporal endExclusive, TemporalUnit unit):计算两个日期时间之间的差值,返回指定时间单位的结果

示例代码:

LocalDate date1 = LocalDate.of(2022, 1, 1);
LocalDate date2 = LocalDate.of(2023, 1, 1);

boolean isBefore = date1.isBefore(date2);
boolean isAfter = date1.isAfter(date2);
boolean isEqual = date1.isEqual(date2);

long daysBetween = ChronoUnit.DAYS.between(date1, date2);// 计算两个日期之间的天数差

Instant类 和 Date类互转

Java 8 提供了 Instant 类来表示时间戳,它表示的是从1970-01-01T00:00:00Z(UTC)开始的时间。Instant 类与 Date 类之间可以进行互转。

常用方法:

  • Date.from(Instant instant):将 Instant 对象转换为 Date 对象
  • Date.toInstant():将 Date 对象转换为 Instant 对象

示例代码:

// 将 Date 对象转换为 Instant 对象
Date date = new Date();
Instant instant = date.toInstant();

// 将 Instant 对象转换为 Date 对象
Instant instant = Instant.now();
Date date = Date.from(instant);

你可能感兴趣的:(java,python,开发语言)