JAVA 核心类
1. String
1.1 **equal**
1.2 **trim**
1.3 **isEmpty**()和**isBlank**()**来判断字符串是否为空和空白字符串:
1.4 替换子串 s.**replace**('l', 'w') or s.**replaceAll**("[\\,\\;\\s]+", ",");
1.5 分割字符串,s.**split**("\\,")
1.6 拼接**join**()
1.7 格式化字符串
<code>
String s = "Hi %s, your score is %d!"
s.formatted("Alice", 80)
String.format("Hi %s, your score is %.2f!", "Bob", 59.5)
</code>
1.9 **StringBuilder**: 为了能高效拼接字符串,Java标准库提供了StringBuilder,它是一个可变对象,可以预分配缓冲区,这样,往StringBuilder中新增字符时,不会创建新的临时对象:
链式操作
var sb = new StringBuilder(1024);
sb.append("Mr ")
.append("Bob")
.append("!")
.insert(0, "Hello, ");
**StringJoiner**: 类似用分隔符拼接数组的需求
String[] names = {"Bob", "Alice", "Grace"};
var sj = new StringJoiner(", ");
for (String name : names) {
sj.add(name);
}
在不需要指定“开头”和“结尾”的时候,用String.join()更方便:
String[] names = {"Bob", "Alice", "Grace"};
var s = String.join(", ", names);
2. Integer
包装类型: 如何把一个基本类型视为对象
自动装箱 :直接把 int变为Integer的赋值写法 Integer n = 100;
自动拆箱: 把Integer变为int的赋值写法,
Integer类:
2.1 parseInt()可以把字符串解析成一个整数:
<code>int x1 = Integer.parseInt("100"); // 100 </code>
<code>int x2 = Integer.parseInt("100", 16); // 256,因为按16进制解析</code>
整数和浮点数的包装类型都继承自Number;
/ 向上转型为Number:
Number num = new Integer(999);
// 获取byte, int, long, float, double:
byte b = num.byteValue();
int n = num.intValue();
long ln = num.longValue();
float f = num.floatValue();
double d = num.doubleValue();
包装类型提供了大量实用方法。
3. JavaBean 若干private实例字段;
通过public方法来读写实例字段。
使用Introspector.getBeanInfo()可以获取属性列表
4. 枚举类
定义常量: 此方法一个严重的问题就是,编译器无法检查每个字段
public class Color {
public static final String RED = "r";
public static final String GREEN = "g";
public static final String BLUE = "b";
}
enum Weekday {
SUN, MON, TUE, WED, THU, FRI, SAT;
}
可使用 == 比较
name() 返回常量名
ordinal()返回定义的常量的顺序,从0开始计数,
5. 记录类 (java 14)
<code>public record Point(int x, int y) {}
使用record关键字,可以一行写出一个不变类
6. BigInteger / BigDecimal
用来表示任意大小的整数。
BigInteger内部用一个int[]数组来模拟一个非常大的整数
BigInteger做运算的时候,只能使用实例方法,例如,加法运算:
BigInteger i1 = new BigInteger("1234567890");
BigInteger i2 = new BigInteger("12345678901234567890");
BigInteger sum = i1.add(i2); // 12345678902469135780
7.常用工具类
1. Math
2. Random
3. SecureRandom