创新互联www.cdcxhl.cn八线动态BGP香港云服务器提供商,新人活动买多久送多久,划算不套路!

导读: 在平时的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();