Object
Object类是所有类的根类,即所有类都直接或间接的继承自Object类。
Object.toString()
jsx
package org.example;
public class Main {
public static void main(String[] args) {
Student s = new Student("John", 25);
System.out.println(s.toString());
// org.example.Student@1be6f5c3 全类名@哈希码 默认调用Object的toString方法
}
}
class Student {
private String name;
private int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
}Object.equals()
jsx
package org.example;
public class Main {
public static void main(String[] args) {
Student s1 = new Student("John", 25);
Student s2 = new Student("Alice", 30);
System.out.println(s2.equals(s1)); // false
System.out.println(s1.equals(s1)); // true
}
}
class Student {
private String name;
private int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
}Objects.isNull
jsx
Objects.isNull(null); // trueObjects.nonNull
jsx
Objects.nonNull(null); // false包装类
包装类的作用是将基本数据类型封装成对象。
| 基本数据类型 | 包装类 |
|---|---|
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
String
StringBuilder
java
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
System.out.println(sb.toString()); // Hello World
System.out.println(sb.reverse().toString()); // dlroW olleH
System.out.println(sb.length()); // 10
}
}StringJoiner
java
public class Main {
public static void main(String[] args) {
StringJoiner sj = new StringJoiner(", ", "[", "]");
sj.add("John");
sj.add("Jane");
sj.add("Jack");
System.out.println(sj); // [John, Jane, Jack]
}
}System
java
package org.example;
import java.util.StringJoiner;
public class Main {
public static void main(String[] args) {
// System 常用方法
System.out.println("Hello World!");
// System.exit(3); // 退出程序
TimeSpend timeSpend = new TimeSpend();
for (int i = 0; i < 100000; i++) {
System.out.print("\r" + i);
}
System.out.println("\nTime spend: " + timeSpend.stop() + "ms"); // Time spend: 153ms
}
}
class TimeSpend{
private final long start;
public TimeSpend(){
start = System.currentTimeMillis();
}
// stop() 方法返回从创建对象到调用 stop() 方法的时间间隔
public long stop(){
return System.currentTimeMillis() - start;
}
}Runtime
java
public class Main {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
System.out.println("Total memory: " + runtime.totalMemory() / 1024 / 1024 + " MB");
System.out.println("Free memory: " + runtime.freeMemory() / 1024 / 1024 + " MB");
System.out.println("Max memory: " + runtime.maxMemory() / 1024 / 1024 + " MB");
// availableProcessors() 方法返回当前系统的 CPU 数目
System.out.println("CPU: " + runtime.availableProcessors());
}
}