Java基础三—Object对象

Object通用方法

public final native Class<?> getClass()

public native int hashCode()

public boolean equals(Object obj)

protected native Object clone() throws CloneNotSupportedException

public String toString()

public final native void notify()

public final native void notifyAll()

public final native void wait(long timeout) throws InterruptedException

public final void wait(long timeout, int nanos) throws InterruptedException

public final void wait() throws InterruptedException

protected void finalize() throws Throwable {}

equals()

equals() 与 ==

  • 对于基本类型,== 判断两个值是否相等,基本类型没有 equals() 方法。
  • 对于引用类型,== 判断两个变量是否引用同一个对象,而 equals() 判断引用的对象是否等价。

hashCode()

hashCode() 返回散列值,而 equals() 是用来判断两个对象是否等价。 等价的两个对象散列值一定相同,但是散列值相同的两个对象不一定等价。

在覆盖 equals() 方法时应当总是覆盖 hashCode() 方法,保证等价的两个对象散列值也相等。

clone()

clone() 是 Object 的 protected 方法,它不是 public,一个类不显式去重写 clone(),其它类就不能直接去调用该类实例的 clone() 方法。

应该注意的是,clone() 方法并不是 Cloneable 接口的方法,而是 Object 的一个 protected 方法。 Cloneable 接口只是规定,如果一个类没有实现 Cloneable 接口又调用了 clone() 方法,就会抛出 CloneNotSupportedException。

  • 浅拷贝
    拷贝对象和原始对象的引用类型引用同一个对象。
  • 深拷贝
    拷贝对象和原始对象的引用类型引用不同对象。

使用 clone() 方法来拷贝一个对象即复杂又有风险,它会抛出异常,并且还需要类型转换。Effective Java 书上讲到,最好不要去使用 clone(),可以使用拷贝构造函数或者拷贝工厂来拷贝一个对象。

&#x8457;&#x4F5C;&#x6743;&#x5F52;https://pdai.tech&#x6240;&#x6709;&#x3002;
&#x94FE;&#x63A5;&#xFF1A;https://pdai.tech/md/java/basic/java-basic-lan-basic.html

public class CloneConstructorExample {
    private int[] arr;

    public CloneConstructorExample() {
        arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i;
        }
    }

    public CloneConstructorExample(CloneConstructorExample original) {
        arr = new int[original.arr.length];
        for (int i = 0; i < original.arr.length; i++) {
            arr[i] = original.arr[i];
        }
    }

    public void set(int index, int value) {
        arr[index] = value;
    }

    public int get(int index) {
        return arr[index];
    }
}
CloneConstructorExample e1 = new CloneConstructorExample();
CloneConstructorExample e2 = new CloneConstructorExample(e1);
e1.set(2, 222);
System.out.println(e2.get(2)); // 2

Q&A

根据 Java 规范,两个使用 equal() 方法来判断相等的对象,必须具有相同的 hash code。

1、hashcode的作用
List和Set,如何保证Set不重复呢?

通过迭代使用equals方法来判断,数据量小还可以接受,数据量大怎么解决? 引入hashcode, 实际上hashcode扮演的角色就是寻址,大大减少查询匹配次数。
2、hashcode重要吗
对于数组、List集合就是一个累赘。而对于hashmap, hashset, hashtable就异常重要了。
3、equals方法遵循的原则

  • 对称性 若x.equals(y)true,则y.equals(x)true
  • 自反性 x.equals(x)必须true
  • 传递性 若x.equals(y)true,y.equals(z)true,则x.equals(z)必为true
  • 一致性 只要x,y内容不变,无论调用多少次结果不变 其他 x.equals(null) 永远false,x.equals(和x数据类型不同)始终false

Original: https://www.cnblogs.com/winter0730/p/15311820.html
Author: cos晓风残月
Title: Java基础三—Object对象

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/576272/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球