类和对象
| |
| new Person().initialize("沉默王二", 18, 1); |
Object类
对象比较
public native int hashCode()
| public native int hashCode(); |
- native方法,用于返回对象的哈希码
- 相等的对象必须具有相等的哈希码。如果重写了 equals 方法,就应该重写 hashCode 方法
public boolean equals(Object obj)
| public boolean equals(Object obj) { |
| return (this == obj); |
| } |
- 比较 2 个对象的内存地址是否相等
- 如果比较的是两个对象的值是否相等,就要重写该方法
| class Person { |
| private String name; |
| private Integer age; |
| |
| |
| |
| @Override |
| public boolean equals(Object o) { |
| |
| if (this == o) return true; |
| |
| if (o == null || getClass() != o.getClass()) return false; |
| |
| Person person = (Person) o; |
| return Objects.equals(name, person.name) && Objects.equals(age, person.age); |
| } |
| |
| |
| @Override |
| public int hashCode() { |
| return Objects.hash(name, age); |
| } |
| } |
对象拷贝
protected native Object clone() throws CloneNotSupportedException;
| protected native Object clone() throws CloneNotSupportedException; |
- naitive 方法,返回此对象的一个副本。默认实现只做浅拷贝,且类必须实现 Cloneable 接口。
对象转字符串
public String toString()
| public String toString() { |
| return getClass().getName() + "@" + Integer.toHexString(hashCode()); |
| } |
- 默认实现返回类名@哈希码的十六进制表示,通常重写返回有含义的字符串。
- 数组也是一个对象
多线程调度
public final void wait() throws InterruptedException
- 调用该方法会导致当前线程等待,直到另一个线程调用此对象的
notify()
方法或notifyAll()
方法。
public final native void notify()
- 唤醒在此对象监视器上等待的单个线程。如果有多个线程等待,选择一个线程被唤醒。
public final native void notifyAll()
public final native void wait(long timeout) throws InterruptedException
- 等待 timeout 毫秒,如果在 timeout 毫秒内没有被唤醒,会自动唤醒。
public final void wait(long timeout, int nanos) throws InterruptedException
- 更加精确了,等待 timeout 毫秒和 nanos 纳秒,如果在 timeout 毫秒和 nanos 纳秒内没有被唤醒,会自动唤醒。
| public static void main(String[] args) { |
| |
| Object o = new Object(); |
| new Thread(() -> { |
| synchronized (o) { |
| try { |
| System.out.println("线程1开始等待"); |
| o.wait(); |
| } catch (InterruptedException e) { |
| e.printStackTrace(); |
| } |
| System.out.println("线程1被唤醒"); |
| } |
| }).start(); |
| new Thread(() -> { |
| synchronized (o) { |
| System.out.println("线程2唤醒线程1开始"); |
| o.notify(); |
| System.out.println("线程2唤醒线程1结束"); |
| } |
| }).start(); |
| } |
反射
| public static void main(String[] args) { |
| Person person = new Person(); |
| Class<? extends Person> aClass = person.getClass(); |
| |
| System.out.println(aClass.getName()); |
| } |
垃圾回收
protected void finalize() throws Throwable
- 当垃圾回收器决定回收对象占用的内存时调用此方法。用于清理资源,但 Java 不推荐使用,因为它不可预测且容易导致问题,Java 9 开始已被弃用。
本文作者:n1ce2cv
本文链接:https://www.cnblogs.com/sprinining/p/18300991
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步