文章目录
- 前言
- 一、Object类
- 二、Objects
- 三、String类
- String的创建
- String类的方法
- length()
- charAt(int index)
- substring(int beginIndex)
- substring(int beginIndex, int endIndex)
- startsWith(String prefix)
- endsWith(String suffix)
- replace(char oldChar, char newChar)
- replace(CharSequence target, CharSequence replacement)
- toLowerCase()
- toUpperCase()
- getBytes():转字节数组
- split(String regex)
- concat(String str)
- valueOf()
- 四、Math类
- 总结
前言
这次我们来总结一下Java常用的类和里面的一些方法。
一、Object类
Object 类是 Java 中所有类的根类,定义了一些常用的方法,可以在所有对象中使用。
toString()
方法签名:public String toString()
返回对象的字符串表示。默认实现返回对象的类名和哈希码的十六进制表示。
示例:
public class ObjectToStringExample {
public static void main(String[] args) {
Person person = new Person("John", 25);
System.out.println(person.toString()); // 输出:Person{name=John, age=25}
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name=" + name + ", age=" + age + "}";
}
}
equals()
方法签名:public boolean equals(Object obj)
比较当前对象和指定对象是否相等。默认实现比较对象的引用是否相等,可以通过重写实现自定义的相等性判断。
示例:
public class ObjectEqualsExample {
public static void main(String[] args) {
Person person1 = new Person("John", 25);
Person person2 = new Person("John", 25);
System.out.println(person1.equals(person2)); // 输出:false
String str1 = "Hello";
String str2 = "Hello";
System.out.println(str1.equals(str2)); // 输出:true
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Person person = (Person) obj;
return age == person.age && Objects.equals(name, person.name);
}
}
equals()方法只能比较引用类型,“==”可以比较引用类型及基本类型;
在equals和“==”进行比较的时候,引用类型数据比较的是引用,即内存地址,基本数据类型比较的是值。
equals()方法 | == | |
---|---|---|
基本数据类型 | 不支持 | 使用数值进行比较 |
引用数据类型 | 支持 | 使用内存地址进行比较 |
覆盖equals()
在使用时,如果我们想要自定义对数据的比较,可以通过覆盖方法,使用自定义的比较方法。
覆盖 equals() 方法的目的是为了根据对象的特定属性或需要来定义对象的相等性。Java 中的 equals() 方法在默认情况下比较的是两个对象的引用是否相等,即判断是否是同一个对象。然而,在实际开发中,我们通常需要比较对象的属性值,而不仅仅是比较对象的引用。
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Person person = (Person) obj;
return age == person.age && Objects.equals(name, person.name);
}
}
hashCode()
方法签名:public int hashCode()
返回对象的哈希码。默认实现返回对象的内存地址的哈希码,也可以通过重写实现自定义的哈希算法。
示例:
public class ObjectHashCodeExample {
public static void main(String[] args) {
Person person = new Person("John", 25);
System.out.println(person.hashCode()); // 输出:-1571746545
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
二、Objects
Objects 类是 Java 提供的一个实用工具类,包含处理对象的常用方法,用于处理对象的比较、哈希码计算和对象的 null 安全操作。
equals(Object a, Object b)
方法签名:public static boolean equals(Object a, Object b)
在比较两个对象的时候,Object.equals方法容易抛出空指针异常。
如果是两个变量比较的时候,就都需要加非空判断。
现在,Objects.equals方法中已经做了非空判断,所以不会抛出空指针异常,它是null-save空指针安全的,而且也可以简化代码。
示例:
import java.util.Objects;
public class ObjectsEqualsExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String str3 = "Hello";
System.out.println(Objects.equals(str1, str2)); // 输出:false
System.out.println(Objects.equals(str1, str3)); // 输出:true
}
}
hashCode(Object obj)
方法签名:public static int hashCode(Object obj)
返回对象的哈希码。该方法处理了 null 值的情况,当对象为 null 时,将返回 0,否则将调用 obj.hashCode() 方法获取哈希码。
示例:
import java.util.Objects;
public class ObjectsHashCodeExample {
public static void main(String[] args) {
String str = "Hello";
System.out.println(Objects.hashCode(str)); // 输出:69609650
}
}
isNull(Object obj)
方法签名:public static boolean isNull(Object obj)
检查对象是否为 null。该方法处理了 null 值的情况,当对象为 null 时,将返回 true,否则返回 false。
示例:
import java.util.Objects;
public class ObjectsIsNullExample {
public static void main(String[] args) {
String str = null;
System.out.println(Objects.isNull(str)); // 输出:true
}
}
nonNull(Object obj)
方法签名:public static boolean nonNull(Object obj)
检查对象是否不为 null。该方法处理了 null 值的情况,当对象不为 null 时,将返回 true,否则返回 false。
示例:
import java.util.Objects;
public class ObjectsNonNullExample {
public static void main(String[] args) {
String str = "Hello";
System.out.println(Objects.nonNull(str)); // 输出:true
}
}
三、String类
String的创建
创建时同时赋值。
String color = 'yellow';
color是String类型的引用。
“yellow” 存在String常量池中,一旦定义值就不能改变
,如果更改其值,只能是让变量指向新的内存空间。
如果采用 new 的方法定义 String,那么是需要分配堆内存空间的,如下:
String str = new String("Hello");
String类的方法
length()
方法签名:public int length()
返回字符串的长度,即字符串中字符的个数。
示例:
String str = "Hello, World!";
int length = str.length();
System.out.println(length); // 输出:13
charAt(int index)
方法签名:public char charAt(int index)
返回字符串中指定位置的字符。
示例:
String str = "Hello, World!";
char ch = str.charAt(7);
System.out.println(ch); // 输出:W
substring(int beginIndex)
方法签名:public String substring(int beginIndex)
返回从指定位置开始到字符串末尾的子字符串。
示例:
String str = "Hello, World!";
String substring = str.substring(7);
System.out.println(substring); // 输出:World!
substring(int beginIndex, int endIndex)
方法签名:public String substring(int beginIndex, int endIndex)
返回从指定开始位置到指定结束位置之间的子字符串,不包括结束位置的字符。
示例:
String str = "Hello, World!";
String substring = str.substring(7, 12);
System.out.println(substring); // 输出:World
startsWith(String prefix)
方法签名:public boolean startsWith(String prefix)
检查字符串是否以指定的前缀开始。
示例:
String str = "Hello, World!";
boolean startsWithHello = str.startsWith("Hello");
System.out.println(startsWithHello); // 输出:true
endsWith(String suffix)
方法签名:public boolean endsWith(String suffix)
检查字符串是否以指定的后缀结束。
示例:
String str = "Hello, World!";
boolean endsWithWorld = str.endsWith("World!");
System.out.println(endsWithWorld); // 输出:true
replace(char oldChar, char newChar)
方法签名:public String replace(char oldChar, char newChar)
将字符串中所有的 oldChar 字符替换为 newChar 字符,并返回替换后的新字符串。
示例:
String str = "Hello, World!";
String newStr = str.replace('o', '*');
System.out.println(newStr); // 输出:Hell*, W*rld!
replace(CharSequence target, CharSequence replacement)
方法签名:public String replace(CharSequence target, CharSequence replacement)
将字符串中所有出现的 target 字符序列替换为 replacement 字符序列,并返回替换后的新字符串。
示例:
String str = "Hello, World!";
String newStr = str.replace("Hello", "Hi");
System.out.println(newStr); // 输出:Hi, World!
toLowerCase()
方法签名:public String toLowerCase()
将字符串中的所有字符转换为小写。
示例:
String str = "Hello, World!";
String lowercase = str.toLowerCase();
System.out.println(lowercase); // 输出:hello, world!
toUpperCase()
方法签名:public String toUpperCase()
将字符串中的所有字符转换为大写。
示例:
String str = "Hello, World!";
String uppercase = str.toUpperCase();
System.out.println(uppercase); // 输出:HELLO, WORLD!
getBytes():转字节数组
方法签名:public byte[] getBytes()
String str = "Hello, World!";
byte[] bytes = str.getBytes();
System.out.println(Arrays.toString(bytes)); // 输出:[72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]
split(String regex)
方法签名:public String[] split(String regex)
根据指定的正则表达式作为分隔符,将字符串拆分为子字符串的数组。
示例:
String str = "Hello,World,Java";
String[] parts = str.split(",");
System.out.println(Arrays.toString(parts)); // 输出:[Hello, World, Java]
concat(String str)
方法签名:public String concat(String str)
将指定的字符串 str 连接到调用该方法的字符串的末尾,形成一个新的字符串并返回。
示例:
String str1 = "Hello";
String str2 = "World";
String result = str1.concat(str2);
System.out.println(result); // 输出:HelloWorld
valueOf()
方法签名:public static String valueOf(Object obj)
将给定的对象 obj 转换为字符串表示形式,并返回结果字符串。
示例:
int number = 42;
String str = String.valueOf(number);
System.out.println(str); // 输出:42
四、Math类
Math 类是 Java 标准库中的一个数学工具类,提供了各种数学运算的静态方法。
以下是 Math 类中常用的一些方法:
常量
Math.PI:表示圆周率 π 的近似值(约为 3.141592653589793)。
数学运算
Math.abs(x):返回参数 x 的绝对值。
int num = -3;
int absNum = Math.abs(num);
System.out.println("绝对值:" + absNum); // 输出:绝对值:3
Math.sqrt(x):返回参数 x 的平方根。
double number = 16.0;
double sqrt = Math.sqrt(number);
System.out.println("平方根:" + sqrt); // 输出:平方根:4.0
Math.pow(x, y):返回 x 的 y 次幂。
double base = 2.0;
double exponent = 3.0;
double result = Math.pow(base, exponent);
System.out.println("指数计算:" + result); // 输出:指数计算:8.0
Math.exp(x):返回 e 的 x 次幂,其中 e 是自然对数的底。
Math.log(x):返回参数 x 的自然对数(以 e 为底)。
Math.log10(x):返回参数 x 的以 10 为底的对数。
Math.sin(x)、Math.cos(x)、Math.tan(x):返回参数 x 的正弦、余弦、正切值,其中 x 用弧度表示。
double angle = Math.toRadians(60.0); // 将角度转换为弧度
double sinValue = Math.sin(angle);
double cosValue = Math.cos(angle);
double tanValue = Math.tan(angle);
System.out.println("正弦值:" + sinValue); // 输出:正弦值:0.86602540378
System.out.println("余弦值:" + cosValue); // 输出:余弦值:0.5
System.out.println("正切值:" + tanValue); // 输出:正切值:1.73205080757
Math.asin(x)、Math.acos(x)、Math.atan(x):返回参数 x 的反正弦、反余弦、反正切值,其中结果用弧度表示。
Math.toDegrees(x):将以弧度表示的角度转换为以度为单位的角度。
Math.toRadians(x):将以度为单位的角度转换为以弧度为单位的角度。
取整和取近似值
Math.ceil(x):返回大于或等于参数 x 的最小整数(向上取整)。
Math.floor(x):返回小于或等于参数 x 的最大整数(向下取整)。
Math.round(x):返回参数 x 四舍五入后的最接近的整数。
Math.max(x, y):返回参数 x 和 y 中的较大值。
Math.min(x, y):返回参数 x 和 y 中的较小值。
随机数
Math.random():返回一个大于等于 0.0 且小于 1.0 的随机数。
double randomNum = Math.random();
System.out.println("随机数:" + randomNum);
总结
今天介绍了一部分的常用类,明天继续。😁😁