Class Object

时间:2023-03-10 04:05:09
Class Object
java.lang

Class Object

  • java.lang.Object

  • public class Object
    Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
Methods 
Modifier and Type Method and Description
protected Object clone()
Creates and returns a copy of this object.
boolean equals(Object obj)
Indicates whether some other object is "equal to" this one.
protected void finalize()
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
Class<?> getClass()
Returns the runtime class of this Object.
int hashCode()
Returns a hash code value for the object.
void notify()
Wakes up a single thread that is waiting on this object's monitor.
void notifyAll()
Wakes up all threads that are waiting on this object's monitor.
String toString()
Returns a string representation of the object.
void wait()
Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
void wait(long timeout)
Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
void wait(long timeout, int nanos)
Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.
1、equals()方法:用于测试某个对象是否同另一个对象相等。它在Object类中的实现是判断两个对象是否指向同一块内存区域。这种测试用处不大,因为即使内容相同的对象,内存区域也是不同的。如果想测试对象是否相等,就需要覆盖此方法,进行更有意义的比较。例如
 class Employee{
... //此例子来自《java核心技术》卷一
public boolean equals(Object otherObj){ //快速测试是否是同一个对象
if(this == otherObj) return true; //如果显式参数为null,必须返回false
if(otherObj == null) reutrn false; //如果类不匹配,就不可能相等
if(getClass() != otherObj.getClass()) return false; //现在已经知道otherObj是个非空的Employee对象
Employee other = (Employee)otherObj; //测试所有的字段是否相等
return name.equals(otherName)
&& salary == other.salary
&& hireDay.equals(other.hireDay);
}
}
对于Object类的equals()方法来说,它判断调用equals()方法的引用于传进来的引用是否一致,即这两个引用是否指向的是同一个对象。

  Object类中的equals()方法如下:

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

  即Object类中的equals()方法等价于==。

  只有当继承Object的类覆写(override)了equals()方法之后,继承类实现了用equals()方法比较两个对象是否相等,才可以说equals()方法与==的不同。

约定:对于任何非空引用x,x.equals(null)应该返回为false。

  并且覆写equals()方法时,应该同时覆写hashCode()方法,反之亦然。

int hashCode()

  Returns a hash code value for the object.

  当你覆写(override)了equals()方法之后,必须也覆写hashCode()方法,反之亦然。

  这个方法返回一个整型值(hash code value),如果两个对象被equals()方法判断为相等,那么它们就应该拥有同样的hash code。

  Object类的hashCode()方法为不同的对象返回不同的值,Object类的hashCode值表示的是对象的地址。

  即,两个对象用equals()方法比较返回false,它们的hashCode可以相同也可以不同。但是,应该意识到,为两个不相等的对象产生两个不同的hashCode可以改善哈希表的性能。