记录重要知识点,避免被知识遗忘。
- 字符串
- StringBuilder
- 包装类(Wrapper Class)
- 枚举类
- 常用工具类
当我们想要比较两个字符串是否相同时,要特别注意,我们实际上是想比较字符串的内容是否相同。必须使用`equals()`方法而不能用`==`;
使用`trim()`方法可以移除字符串首尾空白字符。空白字符包括空格,`t,r,n`;
`strip()`方法也可以移除字符串首尾空白字符。它和`trim()`不同的是,类似中文的空格字符`u3000`也会被移除
String类还提供了多种方法来搜索子串、提取子串
// 搜索子串:
"Hello".contains("ll"); // true
"Hello".indexOf("l"); // 2
"Hello".lastIndexOf("l"); // 3
"Hello".startsWith("He"); // true
"Hello".endsWith("lo"); // true
//提取子串的例子:
"Hello".substring(2); // "llo"
"Hello".substring(2, 4); "ll"
替换子串
要在字符串中替换子串,一种是根据字符或字符串替换:
String s = "hello";
s.replace('l', 'w'); // "hewwo",所有字符'l'被替换为'w'
s.replace("ll", "~~"); // "he~~o",所有子串"ll"被替换为"~~"
拼接字符串
拼接字符串使用静态方法join(),它用指定的字符串连接字符串数组:
String[] arr = {"A", "B", "C"};
String s = String.join("***", arr); // "A***B***C"
格式化字符串
字符串提供了formatted()方法和format()静态方法,可以传入其他参数,替换占位符,然后生成新的字符串:
// String
public class Main {
public static void main(String[] args) {
String s = "Hi %s, your score is %d!";
System.out.println(s.formatted("Alice", 80));
System.out.println(String.format("Hi %s, your score is %.2f!", "Bob", 59.5));
}
}
有几个占位符,后面就传入几个参数。参数类型要和占位符一致。我们经常用这个方法来格式化信息。常用的占位符有:
`%s`:显示字符串;
`%d`:显示整数;
`%x`:显示十六进制整数;
`%f`:显示浮点数。
占位符还可以带格式,例如%.2f表示显示两位小数。如果你不确定用啥占位符,那就始终用%s,因为%s可以显示任何数据类型。要查看完整的格式化语法,请参考JDK文档。
类型转换
要把任意基本类型或引用类型转换为字符串,可以使用静态方法`valueOf()`
String和char[]类型可以互相转换,方法是:
char[] cs = "Hello".toCharArray(); // String -> char[]
String s = new String(cs); // char[] -> String
如果修改了`char[]`数组,`String`并不会改变:这是因为通过`new String(char[])`创建新的`String`实例时,它并不会直接引用传入的`char[]`数组,而是会复制一份,所以,修改外部的`char[]`数组不会影响`String`实例内部的`char[]`数组,因为这是两个不同的数组。
删除子串
String s = "zheshigezifuchuan";
s.delete(int start, int end);//start:起始索引(包括);end:结束索引(不包括);
`start`:起始索引(包括);`end`:结束索引(不包括);
2. StringBuilder
为了能高效拼接字符串,Java标准库提供了StringBuilder,它是一个可变对象,可以预分配缓冲区,这样,往StringBuilder中新增字符时,不会创建新的临时对象:
StringBuilder sb = new StringBuilder(1024);
for (int i = 0; i < 1000; i++) {
sb.append(',');
sb.append(i);
}
String s = sb.toString();
3.包装类(Wrapper Class)
- - 基本类型:`byte`,`short`,`int`,`long`,`boolean`,`float`,`double`,`char`
- - 引用类型:所有`class`和`interface`类型(`String`也是一个`class`类型)
为了让基本数据类型也具备对象的特性, Java 为每个基本数据类型都提供了一个包装类,这样我们就可以像操作对象那样来操作基本数据类型。
包装类主要提供了两大类方法:
1. 将本类型和其他基本类型进行转换的方法
2. 将字符串和本类型及包装类互相转换的方法
//创建integer
public class Main {
public static void main(String[] args) {
int i = 100;
// 通过new操作符创建Integer实例(不推荐使用,会有编译警告):
Integer n1 = new Integer(i);
// 通过静态方法valueOf(int)创建Integer实例:
Integer n2 = Integer.valueOf(i);
// 通过静态方法valueOf(String)创建Integer实例:
Integer n3 = Integer.valueOf("100");
System.out.println(n3.intValue());
}
}
//类型转换
public class HelloWorld {
public static void main(String[] args) {
// 定义int类型变量,值为86
int score1 = 86;
// 创建Integer包装类对象,表示变量score1的值
Integer score2=new Integer(score1);
// 将Integer包装类转换为double类型
double score3=score2.doubleValue();
// 将Integer包装类转换为float类型
float score4=score2.floatValue();
// 将Integer包装类转换为int类型
int score5 =score2.intValue();
System.out.println("Integer包装类:" + score2);
System.out.println("double类型:" + score3);
System.out.println("float类型:" + score4);
System.out.println("int类型:" + score5);
}
}
所有的整数和浮点数的包装类型都继承自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();
4.枚举类
使用enum来定义枚举类:
// enum
public class Main {
public static void main(String[] args) {
Weekday day = Weekday.SUN;
if (day == Weekday.SAT || day == Weekday.SUN) {
System.out.println("Work at home!");
} else {
System.out.println("Work at office!");
}
}
}
enum Weekday {
SUN, MON, TUE, WED, THU, FRI, SAT;
}
1. enum常量本身带有类型信息,即Weekday.SUN类型是Weekday,编译器会自动检查出类型错误。
2. 不可能引用到非枚举的值,因为无法通过编译。
3. 不同类型的枚举不能互相比较或者赋值,因为类型不符。
4. 因为enum类型的每个常量在JVM中只有一个唯一实例,所以可以直接用==比较
name()返回常量名,例如:
String s = Weekday.SUN.name(); // "SUN"
ordinal()返回定义的常量的顺序,从0开始计数,例如:
int n = Weekday.MON.ordinal(); // 1
5.常用工具类
Math
求绝对值
Random
Random用来创建伪随机数。所谓伪随机数,是指只要给定一个初始的种子,产生的随机数序列是完全一样的。
要生成一个随机数,可以使用nextInt()、nextLong()、nextFloat()、nextDouble():
Random
如果我们在创建Random实例时指定一个种子,就会得到完全确定的随机数序列
SecureRandom
有伪随机数,就有真随机数。实际上真正的真随机数只能通过量子力学原理来获取,而我们想要的是一个不可预测的安全的随机数,SecureRandom就是用来创建安全的随机数的:
SecureRandom sr = new SecureRandom();
System.out.println(sr.nextInt(100));
参考:Java核心类