一篇学习Java Object的常见方法

一、getClass

  • public final native Class<?> getClass()
    • 意义返回Object运行
    • 作用常用反射类型检查
    • 使用场景需要知道一个对象实际类型可以使用
public class GetClassExample {
    public static void main(String[] args) {
        GetClassExample example = new GetClassExample(); // 创建对象
        // 打印对象的运行时类
        System.out.println("对象的类是: " + example.getClass().getName());
    }
}

二、hashCode

  • public native int hashCode()
    • 意义返回对象哈希码
    • 作用哈希确定对象存储位置
    • 使用场景需要自定义对象作为哈希表需要重写hashcode方法
public class HashCodeExample {
    private int id; // 对象的标识符

    public HashCodeExample(int id) {
        this.id = id; // 初始化标识符
    }

    @Override
    public int hashCode() {
        return id; // 返回对象的哈希码值
    }

    public static void main(String[] args) {
        HashCodeExample example = new HashCodeExample(123); // 创建对象并设置ID
        // 打印对象的哈希码值
        System.out.println("对象的哈希码是: " + example.hashCode());
    }
}

三、equals

  • public boolean equals(Object obj)
    • 意义某个对象是否对象相等
    • 作用比较两个对象是否相等
    • 使用场景当需要自定义对象相等逻辑需要重写equals方法(重写equals方法,同时也要重写hashcode,要保证它们一致性)
public class EqualsExample {
    private int id; // 对象的标识符

    public EqualsExample(int id) {
        this.id = id; // 初始化标识符
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true; // 如果两个对象引用相同,返回true
        if (obj == null || getClass() != obj.getClass()) return false; // 如果对象为null或类不同,返回false
        EqualsExample that = (EqualsExample) obj; // 类型转换
        return id == that.id; // 比较标识符
    }

    public static void main(String[] args) {
        EqualsExample example1 = new EqualsExample(123); // 创建第一个对象
        EqualsExample example2 = new EqualsExample(123); // 创建第二个对象
        // 打印两个对象是否相等
        System.out.println("对象是否相等: " + example1.equals(example2));
    }
}

四、clone

  • public native Object clone()
    • 意义创建返回对象一个副本
    • 作用实现对象浅拷贝
    • 使用场景:需要复制一个对象但是不希望两个对象引用同一个内存地址使用并且 clone方法受保护 需要实现一个Cloneable接口再去重写clone方法 调用super.clone()
public class CloneExample implements Cloneable {
    private int id; // 对象的标识符

    public CloneExample(int id) {
        this.id = id; // 初始化标识符
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone(); // 调用父类的clone方法
    }

    public static void main(String[] args) {
        try {
            CloneExample example1 = new CloneExample(123); // 创建对象
            CloneExample example2 = (CloneExample) example1.clone(); // 克隆对象
            // 打印克隆对象的ID
            System.out.println("克隆对象的ID是: " + example2.id);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace(); // 捕获并打印异常
        }
    }
}

五、toString

  • public String toString()
    • 意义返回对象字符串表示
    • 作用方便打印对象信息转换字符串
    • 使用场景需要打印对象信息对象转换字符串通常需要重写toString方法
public class ToStringExample {
    private int id; // 对象的标识符

    public ToStringExample(int id) {
        this.id = id; // 初始化标识符
    }

    @Override
    public String toString() {
        return "ToStringExample{id=" + id + '}'; // 返回对象的字符串表示
    }

    public static void main(String[] args) {
        ToStringExample example = new ToStringExample(123); // 创建对象
        // 打印对象的字符串表示
        System.out.println("对象的字符串表示: " + example.toString());
    }
}

六、notify

  • public final native void notify()
    • 意义唤醒对象监视器等待单个线程
    • 作用用于线程同步实现线程通信
    • 使用场景线程调用一个对象 wait方法另一个线程可以通过使用notify()notifyAll方法唤醒等待线程
class NotifyExample {
    private final Object lock = new Object(); // 锁对象

    public void waitingThread() {
        synchronized (lock) {
            try {
                System.out.println(Thread.currentThread().getName() + " 正在等待...");
                lock.wait(); // 进入等待状态
                System.out.println(Thread.currentThread().getName() + " 已经恢复!");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 处理中断异常
            }
        }
    }

    public void notifyingThread() {
        synchronized (lock) {
            lock.notify(); // 唤醒一个等待线程
            System.out.println(Thread.currentThread().getName() + " 已通知一个线程.");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        NotifyExample example = new NotifyExample(); // 创建示例对象
        Thread t1 = new Thread(example::waitingThread, "线程-1");
        Thread t2 = new Thread(example::waitingThread, "线程-2");

        t1.start(); // 启动第一个线程
        t2.start(); // 启动第二个线程

        Thread.sleep(1000); // 确保两个线程进入等待状态
        new Thread(example::notifyingThread, "通知线程").start(); // 启动通知线程
    }
}

七、notifyAll

  • public final native void notifyAll()
    • 意义唤醒对象监视器等待所有线程
    • 作用用于多线程同步实现线程通信唤醒所有等待线程
    • 使用场景唤醒所有线程
class NotifyAllExample {
    private final Object lock = new Object(); // 锁对象

    public void waitingThread() {
        synchronized (lock) {
            try {
                System.out.println(Thread.currentThread().getName() + " 正在等待...");
                lock.wait(); // 进入等待状态
                System.out.println(Thread.currentThread().getName() + " 已经恢复!");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 处理中断异常
            }
        }
    }

    public void notifyingThread() {
        synchronized (lock) {
            lock.notifyAll(); // 唤醒所有等待线程
            System.out.println(Thread.currentThread().getName() + " 已通知所有线程.");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        NotifyAllExample example = new NotifyAllExample(); // 创建示例对象
        Thread t1 = new Thread(example::waitingThread, "线程-1");
        Thread t2 = new Thread(example::waitingThread, "线程-2");

        t1.start(); // 启动第一个线程
        t2.start(); // 启动第二个线程

        Thread.sleep(1000); // 确保两个线程进入等待状态
        new Thread(example::notifyingThread, "通知线程").start(); // 启动通知线程
    }
}

八、wait

  • public final native void wait(long timeout);
    • 意义使当前线程等待直到其他线程调用对象notifynotifyAll方法
    • 作用用于多线程同步使线程进入等待状态
    • 使用场景需要多线程环境实现等待/通知机制使用wait 方法
class WaitTimeoutExample {
    private final Object lock = new Object(); // 锁对象

    public void waitingThread() {
        synchronized (lock) {
            try {
                System.out.println(Thread.currentThread().getName() + " 正在等待 2 秒...");
                lock.wait(2000); // 等待2秒
                System.out.println(Thread.currentThread().getName() + " 已经恢复!");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 处理中断异常
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        WaitTimeoutExample example = new WaitTimeoutExample(); // 创建示例对象
        Thread t1 = new Thread(example::waitingThread, "线程-1");

        t1.start(); // 启动线程
        t1.join(); // 等待线程结束
    }
}

九、wait

​​​​​​
  • public final native void wait(long timeout, int nanos)
    • 意义提供了更为精准等待时间
    • 作用用于多线程同步使线程进入等待状态
    • 使用场景
      • 高精度定时等待线程非常精确时间唤醒
      • 等待特定事件发生在特定事件发生并且等待时间需要精确控制
      • 同步协调同步协调多个线程执行使得线程能够特定时间得到控制
class WaitNanosExample {
    private final Object lock = new Object(); // 锁对象

    public void waitingThread() {
        synchronized (lock) {
            try {
                System.out.println(Thread.currentThread().getName() + " 正在等待 2 秒和 500 纳秒...");
                lock.wait(2000, 500); // 等待2秒和500纳秒
                System.out.println(Thread.currentThread().getName() + " 已经恢复!");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 处理中断异常
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        WaitNanosExample example = new WaitNanosExample(); // 创建示例对象
        Thread t1 = new Thread(example::waitingThread, "线程-1");

        t1.start(); // 启动线程
        t1.join(); // 等待线程结束
    }
}

十、finalize

    • 意义当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。
    • 作用允许对象在垃圾回收之前执行清理操作。
    • 使用场景
      • 资源释放在对象销毁之前释放资源比如关闭文件数据库链接网络连接
      • 临时文件删除删除对象创建临时文件确保对象销毁时不留下临时文件
      • 内存资源清理处理内存资源清理工作释放一些操作系统资源
public class FinalizeExample {
    @Override
    protected void finalize() throws Throwable {
        // 在垃圾回收之前执行清理操作
        System.out.println("对象正在被垃圾回收");
    }

    public static void main(String[] args) {
        FinalizeExample example = new FinalizeExample(); // 创建对象
        example = null; // 将对象置为null,使其可被垃圾回收

        System.gc(); // 请求垃圾回收

        // 给垃圾回收一些时间运行
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // 处理中断异常
        }
    }
}

  • 21
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序是我的命

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值