当前位置: 移动技术网 > IT编程>开发语言>Java > 关于Java Object你真的了解了吗

关于Java Object你真的了解了吗

2019年07月22日  | 移动技术网IT编程  | 我要评论

导读: 在平时的coding中hashcode()和equals()的使用的场景有哪些?clone深复制怎么实现?wait()和notify()有什么作用?finalize()方法干嘛的?看似coding中使用的不多,不重要,但是有没有跟我一样,想好好的了解一下的。毕竟是基础中的基础。

下面给出一个简单比较全面的概要:

1. hashcode()和equals()

public boolean equals(object obj) {return (this == obj);}

public native int hashcode();

1.当equals()方法被override时,hashcode()也要被override.

2.当equals()返回true,hashcode一定相等。即:相等(相同)的对象必须具有相等的哈希码(或者散列码)

3.如果两个对象的hashcode相同,它们并不一定相同。

4.在集合查找时,hashcode能大大降低对象比较次数,提高查找效率!

在判断重复元素时,直接通过hashcode()方法,定位到桶位置,如果该位置有元素,再调用equals()方法判断是否相等。而不是遍历每一个元素比较equals()!

2. clone() 深复制

public class animal implements cloneable {
  private int height;
  private int age;

  public animal(int height, int age){
    this.height = height;
    this.age = age;
  }

  @override
  public object clone() throws clonenotsupportedexception {
    return super.clone();
  }
}


public class people implements cloneable {
  private int height;
  private int age;
  private animal a;

  public people(int height, int age,animal a){
    this.height = height;
    this.age = age;
    this.a = a;
  }

  @override
  public object clone() throws clonenotsupportedexception {
    people p = (people) super.clone();
    p.a = (animal) a.clone();
    return p;
  }

}

animal a1 = new animal(100,3);
people p1 = new people(173,24,a1);
//深复制
people p2 = (people) p1.clone();

3. wait()和notify()

•只有获得该对象锁之后才能调用,否则抛illegalmonitorstateexception异常

•任何一个时刻,对象的控制权(monitor)只能被一个线程拥有。

线程取得控制权的方法有三:

1. 执行对象的某个同步实例方法。

2. 执行对象对应类的同步静态方法。

3. 执行对该对象加同步锁的同步块。

执行对该对象加同步锁的示例:

  synchronized (pepoleobject) {
    pepoleobject.notifyall();
    pepoleobject.wait();
  }

4. finalize()

当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾加收器调用此方法,只能调用一次。当对象被回收时需要配置系统资源或执行其他清除,子类重写finalize方法实现。

以上这篇关于java object你真的了解了吗就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网