Java 常用 API - Zhangyao719/java-study GitHub Wiki
https://www.runoob.com/manual/jdk11api/java.base/java/lang/Object.html
Object 类是 Java 中所有类的父类。因此,Java 中所有类的对象都可以直接使用 Object 类中提供的方法。
默认返回一个字符串,该字符串由对象为实例的类的名称,符号字符“ <font style="color:rgb(71, 71, 71);">@</font>
”以及对象的哈希码的无符号十六进制表示形式组成。建议所有子类都覆盖此方法。
比较两对象的地址是否一样。
Student s1 = new Student(18, "张三");
Student s2 = new Student(18, "张三");
System.out.println(s1.equals(s2)); // false
System.out.println(s1 == s2); // false
public class Student {
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
}
为什么不用 String 的 equals 而使用 Objects 的 equals 进行 name 的比较呢?
public final class Objects {
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
}
因为 Objects 中的 equals 进行了 null 的校验。所以,比较两个对象时,建议使用 Objects.equals
。
把基本类型的数据包装成对象。
基本数据类型 | 对应的包装类(引用数据类型) |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
char | Character |
float | Float |
double | Double |
boolean | Boolean |
int num1 = 12;
Integer numObj1 = new Integer(num1); // 旧语法
Integer numObj2 = Integer.valueOf(num1); // 新语法
// 简写方式
Integer numObj3 = 12; // 直接将数字转换成对象(自动装箱机制)
int num2 = numObj3 // 直接将对象转换成数字(自动拆箱机制)
public static Integer valueOf(int i) {
// -128 -> 127 之间的数字已经提前缓存好,无需新 new,可以复用
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
// 不再范围内的才会执行 new
return new Integer(i);
}
toString
把基本类型数据转成字符串
int a1 = 23;
String a1Str = Integer.toString(a1); // "23"
Integer a2 = 23;
String a2Str = a2.toString(a2); // "23"
parseInt ★★★
把字符串的数值转换成数值本身对应的数据类型
String ageStr = "23";
int age1 = Integer.parseInt(ageStr); // 23
int age2 = Integer.valueOf(ageStr); // 23
System.out.println(age1 == age2); // true
String ageDbl = "23.5";
double age3 = Double.parseDouble(ageDbl); // 23.5
System.out.println(age3 + 0.5); // 24.0
System.out.println(age3 == age4); // true
可以使用包装类对应的 parse 方法转换,或者直接使用 valueOf
转换。
由于泛型不支持基本数据类型,所以在集合和泛型中大量使用包装类。
StringBuilder 代表可变字符串对象,相当于一个容器,里面装的字符串是可以改变的,用来操作字符串。
StringBuilder 比 String 更适合做字符串的修改操作,效率高,代码简洁。
StringBuilder str = new StringBuilder();
str.append("哈哈").append("呵呵").append("啊啊");
str.reverse();
str.length();
String res = str.toString();
当有大量的字符操作时,推荐使用 StringBuilder。
public static String getArrayData(int[] arr) {
if(arr == null) return
StringBuilder str = new StringBuilder();
str.append("[");
for (int i = 0; i < arr.length; i++) {
str.append(arr[i]).append(i == arr.length - 1 ? "" : ",");
}
str.append("]");
// 返回最终的字符串结果
return str.toString();
}
int [] list = {1,2,3,4,5,6,7,8,9};
String res = getArrayData(list);
System.out.println(res);
功能和 StringBuilder 一样,但是 StringBuilder 线程不安全,StringBuffer 是线程安全的。
<font style="color:rgb(71, 71, 71);">StringJoiner</font>
用于构造由分隔符分隔的字符序列,并且可选地以提供的前缀开头并以提供的后缀结束。
public static String getArrayData(int[] arr) {
if (arr == null) return null;
StringJoiner str = new StringJoiner(", ", "[", "]");
for (int i = 0; i < arr.length; i++) {
// StringJoiner 只支持字符串
str.add(Integer.toString(arr[i]));
}
return str.toString();
}
int [] list = {1,2,3,4,5,6,7,8,9};
String res = getArrayData(list);
System.out.println(res);
方法名 | 说明 |
---|---|
int abs(int a) | 获取参数绝对值 |
double ceil(double a) | 向上取整 |
double floor(double a) | 向下取整 |
int round(float a) | 四舍五入 |
int max(int a, int b) | 获取两个 int 的最大值 |
double pow(double a, double b) | 返回 a 的 b 次幂的值 |
double random() | 返回值为 double 的随机值,范围 [0.0, 1.0) |
代表程序所在的运行时环境;
Runtime 是一个单例类。
方法名 | 说明 |
---|---|
Runtime getRuntime() | 返回与当前Java应用程序关联的运行时对象 |
void exit(int status) | 终止当前运行的虚拟机 返回Java虚拟机可用的处理 |
int availableProcessors() | 返回Java虚拟机可用的处理器数 |
long totalMemory() | 返回Java虚拟机中的内存总量 |
long freeMemory() | 返回lava虚拟机中的可用内存 |
Process exec(String command) | 启动某个程序,并返回代表该程序的对象 |
public static void main(String[] args) {
Runtime jre = Runtime.getRuntime();
// 终止当前虚拟机,status 用作参数代码,非0状态码表示异常终止
// jre.exit(0);
System.out.println("处理器数量:" + jre.availableProcessors());
System.out.println("Java 虚拟机中的内存总量:" + jre.totalMemory() / 1024 / 1024 + "MB");
System.out.println("Java 虚拟机中的可用内存:" + jre.freeMemory() / 1024 / 1024 + "MB");
// 执行命令,启动程序
// Process process = jre.exec(/* */)
}
代表程序所在的系统,也是一个工具类。
方法名 | 说明 |
---|---|
void exit(int status) | 终止当前运行的 Java 虚拟机 |
long currentTimeMillis | 返回当前系统的时间毫秒值形式 |
用于解决浮点型运算结果失真的问题。
构造器 | 说明 |
---|---|
public BigDecimal(double val) | 将 double 转换为 BigDecimal,不推荐使用,无法解决精度问题 |
public BigDecimal(String val) ★★★ | 把 string 转成 BigDecimal |
方法名 | 说明 |
---|---|
public static BigDecimal valueof(double val) | 转换一个 double成 BigDecima1 |
public BigDecimal add(BigDecimalb) | 加法 |
public BigDecimal subtract(BigDecimalb) | 减法 |
public BigDecimal multiply(BigDecimalb) | 乘法 |
public BigDecimal divide(BigDecimal b) | 除法 |
public BigDecimal divide(另一个BigDecimal对象,精确几位,舍入模式) | 除法、可以控制精确到小数几位 |
public double doubleValue() | 将BigDecimal转换为double |
public static void main(String[] args) {
double a = 0.1;
double b = 0.2;
// 方式1. 将两个数据包装成 BigDecimal 对象
// BigDecimal a1 = new BigDecimal(Double.toString(a));
// BigDecimal b1 = new BigDecimal(Double.toString(b));
// 方式2. 阿里更推荐使用 valueOf 包装浮点型整数成为 BigDecimal 对象
// valueOf 内部使用了 new BigDecimal
BigDecimal a11 = BigDecimal.valueOf(a);
BigDecimal b11 = BigDecimal.valueOf(b);
BigDecimal result = a11.add(b11);
double res = result.doubleValue();
System.out.println(result); // 0.3
}
public static void main(String[] args) {
BigDecimal i = BigDecimal.valueOf(0.1);
BigDecimal j = BigDecimal.valueOf(0.3);
BigDecimal k = i.divide(j, 2, RoundingMode.HALF_UP);
System.out.println(k.doubleValue()); // 0.33
}
java.time 包下的类
时间 | 说明 |
---|---|
LocalDate | 年、月、日 |
LocalTime | 时、分、秒 |
LocalDateTime | 年、月、日、时、分、秒 |
ZoneId | 时区 |
ZonedDateTime | 带时区的时间 |
Instant | 时间戳/时间线 |
DateTimeFormatter | 用于时间的格式化和解析 |
Duration | 时间间隔(时、分、秒,纳秒) |
Period | 时间间隔(年,月,日) |
public static void main(String[] args) {
LocalDate date = LocalDate.now();
System.out.println("date = " + date); // 1949-10-01
System.out.println(date.getYear()); // 年
}
方法名 | 说明 |
---|---|
public static String toString(类型[] arr) | 返回数组的内容 |
public staticint[] copyOfRange(类型[ ] arr,起始索引,结束索引) | 拷贝数组(指定范围) |
public static copyOf(类型[] arr, int newLength) | 拷贝数组 |
public static setAll(doublel] array, IntToDoubleFunction generator) | 把数组中的原数据改为新数据 |
public static void sort(类型[] arr) | 对数组进行排序(默认是升序排序) |
// 类自己实现 Comparable 规则比较接口,重写 compareTo 方法,指定比较规则
public class Student implements Comparable<Student> {
@Override
public int compareTo(Student o) {
return this.age - o.age; // 升序
// return o.age - this.age; // 降序
}
}
// sort 存在重载方法,支持自带 Comparator 比较器对象来直接指定比较规则
public class Test {
public static void main(String[] args) {
Student[] list = new Student[2];
list[0] = new Student("张三", 18, '男', 1.72);
list[1] = new Student("李四", 19, '男', 1.82);
// 匿名构造类直接传递比较器对象
Arrays.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// 按 int age 升序
// return o1.getAge() - o2.getAge();
// 按 double height 升序
return Double.compare(o1.getHeight(), o2.getHeight());
}
});
}
}
System.out.println(Arrays.toString(list));
方法名称 | 说明 |
---|---|
public static boolean addAll(collection<? super T>c,T... elements) | 给集合批量添加元素 |
public static void shuffle(List<?> list) | 打乱List集合中的元素顺序 |
public static void sort(List list) | 对List集合中的元素进行升序排序 |
public static void sort(Listlist,comparator<? super T> c) | 对List集合中元素,按照比较器对象指定的规则进行排序 |