Java中Object类的公有方法

  HashCode();wait();notify();equals();getClass();toString();clone();finalize();java

  这里只是简单介绍一下其中的几个函数:函数

  HashCode():学习

     * As much as is reasonably practical, the hashCode method defined by
     * class {@code Object} does return distinct integers for distinct
     * objects. (This is typically implemented by converting the internal
     * address of the object into an integer, but this implementation
     * technique is not required by the
     * Java™ programming language.)

  这个是Java官方文档里的部分解释,简单地说就是返回一个integer类型的值,这个值是经过该Object的内部地址(internal address)转换过来的,这个哈希码是能够经过getClass()方法看到具体值的,显示的是十六进制的数,有时候能够经过此方法来判断对象的引用是否相等,研究java内存的时候,这个可能会有用。ui

  equals():this

  都知道java中比较字符串是否相等应该用equals();而==则是比较的值,也就是引用;那么为何是这样的呢?我今天看了下equals的实现方法,发现字符串的比较,是经过每个字符进行比较,若是都相等,则返回true;而源码里面Object类型的equals方法倒是直接用==来代替的,也就是说至关于直接比较引用了,这也就是为何咱们有时候要重写equals方法了,下面附上Jdk中String类型的equals方法源码。spa

    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;
    }

  getClass(): .net

  toString():线程

  下面的例子中j是一个简单的Java对象,后面分别是toString()方法和getClass()方法的输出,@后面的即为哈希码,也就是内存地址,getClass()返回运行时的类,code

还有getName(),getSimpleName()方法,这些均可以经过查看源码的方法来了解用法,看源码真的是很好的一种学习方法。对象

System.out.println(j.toString());
System.out.println(j.getClass());
com.wust.cvte.j2se@15db9742
class com.wust.cvte.j2se

  clone():

  中文”克隆"的意思,刚开始我看源码里的注释,看的并非很懂,后来又在网上查看一些博客,明白了clone方法其实是实现了浅复制,附上一篇详解此方法的博客,有图有真相,特别详细,http://blog.csdn.net/zhangjg_blog/article/details/18369201#0-qzone-1-28144-d020d2d2a4e8d1a374a433f596ad1440

  其它方法涉及到线程和内存回收,GG等,到用的时候再作记录吧,其中如有不正确之处,欢迎指证。

相关文章
相关标签/搜索