Java基础知识(2)——核心类

记录重要知识点,避免被知识遗忘。

1.字符串

当我们想要比较两个字符串是否相同时,要特别注意,我们实际上是想比较字符串的内容是否相同。必须使用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)

  • 基本类型:byteshortintlongbooleanfloatdoublechar
  • 引用类型:所有classinterface类型(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

求绝对值:
Math.abs(-100); // 100
Math.abs(-7.8); // 7.8

取最大或最小值:
Math.max(100, 99); // 100
Math.min(1.2, 2.3); // 1.2

计算xy次方:
Math.pow(2, 10); // 2的10次方=1024

计算√x:
Math.sqrt(2); // 1.414...

计算ex次方:
Math.exp(2); // 7.389...

计算以e为底的对数:
Math.log(4); // 1.386...

计算以10为底的对数:
Math.log10(100); // 2

三角函数:
Math.sin(3.14); // 0.00159...
Math.cos(3.14); // -0.9999...
Math.tan(3.14); // -0.0015...
Math.asin(1.0); // 1.57079...
Math.acos(1.0); // 0.0

Math还提供了几个数学常量:
double pi = Math.PI; // 3.14159...
double e = Math.E; // 2.7182818...
Math.sin(Math.PI / 6); // sin(π/6) = 0.5

Random

Random用来创建伪随机数。所谓伪随机数,是指只要给定一个初始的种子,产生的随机数序列是完全一样的。
要生成一个随机数,可以使用nextInt()、nextLong()、nextFloat()、nextDouble():

Random r = new Random();
r.nextInt(); // 2071575453,每次都不一样
r.nextInt(10); // 5,生成一个[0,10)之间的int
r.nextLong(); // 8811649292570369305,每次都不一样
r.nextFloat(); // 0.54335...生成一个[0,1)之间的float
r.nextDouble(); // 0.3716...生成一个[0,1)之间的double

如果我们在创建Random实例时指定一个种子,就会得到完全确定的随机数序列

SecureRandom
有伪随机数,就有真随机数。实际上真正的真随机数只能通过量子力学原理来获取,而我们想要的是一个不可预测的安全的随机数,SecureRandom就是用来创建安全的随机数的:

SecureRandom sr = new SecureRandom();
System.out.println(sr.nextInt(100));

参考:Java核心类

奖励自己一张图:在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值