【Java】Object类的方法

来源:互联网 发布:php连接数据库语句 编辑:程序博客网 时间:2024/06/08 13:20

Object的方法有哪些

Object在java.lang包中,该包中有Java的核心基础类,默认导入该包。Object是类分级的根本,Java中几乎所有的类都默认继承了Object类。

Object没有属性,方法如下:

  • private static native void registerNatives()
  • public final native Class<?> getClass()
  • public native int hashCode()
  • 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

1.registerNatives()

private static native void registerNatives()
native修饰的方法,意味着操作系统需要实现该方法(通过C/C++代码实现),Java不需要实现。Object类中有这么一段代码,在static代码块中调用了方法,也就是该类第一次装载到内存中执行一次这个方法,根据网上资料,该方法是用来与操作系统交互的,完成JNI链接。

static {    registerNatives();}

2.getClass()

public final native Class<?> getClass()
返回当前对象指向的类。如下代码输出的是class java.lang.Integer

public class Test {    public static void main(String args[]) {        Number a = new Integer(0);        System.out.println(a.getClass());    }}

3.hashCode()

public native int hashCode()
返回当前对象的hash code value,这个类是用来支持一些hash table,例如HashMap。每个类的hashCode计算规则有两个

  • 如果两个对象通过equal()函数对比相等的话,那么这两个对象的hashCode()返回的int数值必须相等
  • 如果两个对象是不相等,那么hashCode一定不相等
    如果不重写该方法的话,返回值应该是对象的地址转成int数值。一般需要对比的对象,类必须实现该方法以及equals()方法。
public final class Integer extends Number implements Comparable<Integer> {    @Override    public int hashCode() {        return Integer.hashCode(value);    }}

String类的hashCode方法,用h=31 * h + val[i]算法。也就是s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
为什么用31这个权值?

  • 要用基数,如果用偶数,二进制每2进一位,则每位乘以偶数群众,都是向左移位,则数据丢失;
  • 用31是因为31是素数,并且有31 * i == (i << 5) - i该简洁算法,计算机对于移位运算性能好。
    参考 Joshua Bloch’s Effective Java
    The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional. A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance: 31 * i == (i << 5) - i. Modern VMs do this sort of optimization automatically. (from Chapter 3, Item 9: Always override hashcode when you override equals, page 48)
public final class String    implements java.io.Serializable, Comparable<String>, CharSequence {    public int hashCode() {        int h = hash;        if (h == 0 && value.length > 0) {            char val[] = value;            for (int i = 0; i < value.length; i++) {                h = 31 * h + val[i];            }            hash = h;        }        return h;    }} 

4.equals(Object obj)

public boolean equals(Object obj)
判断两个对象是否相等的方法。可以先判断地址是否相等,再判断值是否相等。自定义对象需要重写该方法,不然该方法都是对比地址是否相等。

public class Object {    public boolean equals(Object obj) {        return (this == obj);    }}
看一看String中该方法的实现吧,先判断地址是否相等,再判断类型、字符长度,各个字符是否相等。
public final class String    implements java.io.Serializable, Comparable<String>, CharSequence {public boolean equals(Object anObject) {        if (this == anObject) {            return true;        }        if (anObject instanceof String) {            String anotherString = (String)anObject;            int n = value.length;            if (n == anotherString.value.length) {                char v1[] = value;                char v2[] = anotherString.value;                int i = 0;                while (n-- != 0) {                    if (v1[i] != v2[i])                        return false;                    i++;                }                return true;            }        }        return false;    }}

5.clone()

protected native Object clone() throws CloneNotSupportedException
拷贝对象的方法,返回一个拷贝出来的对象实例,如果这个类不能被克隆,调用该方法则会抛出CloneNotSupportedExceptionObjectclone方法只通过JNI实现对象浅拷贝。
- x.clone() != x
返回的拷贝对象是开辟新的内存。
- x.clone().getClass() == x.getClass()
- x.clone().equals(x)

重写实现clone方法需要注意以下几点

  • 使用clone方法的类需要实现Cloneable接口
    Cloneable并没有声明的方法,所以这个接口相当于一个“标记”的作用,标记该类可以调用clone方法。如果某些类不需要实现clone,就可以不实现该接口,从而达到一个保护的作用。如果没有实现该接口,而去调用clone方法的话则会抛出CloneNotSupportedException
  • 将clone方法声明为public
  • 如果有必要重写clone方法,则需要调用super.clone()

6.toString()

public String toString()
返回该对象的className+”@”+hashCode,可以标示唯一的对象。

7.notify()

public final native void notify()
唤醒等待该对象锁的一个线程。被唤醒的线程等待当前线程释放锁才能获取锁。

8.notifyAll()

public final native void notifyAll()
唤醒等待该对象锁的所有线程。被唤醒的线程等待当前线程释放锁才能通过竞争获取锁。

9.wait()

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
使得当前线程放弃锁,直至其他线程调用notify()或者notifyAll()方法,或者超过参数设置的等待时间(带参方法)。

10.finalize()

protected void finalize() throws Throwable
垃圾收集器回收该对象时,会调用该方法。

0 0
原创粉丝点击