zoukankan      html  css  js  c++  java
  • java源码equals和hashCode

    equals

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

    比较两个对象时,首先先去判断两个对象是否具有相同的地址,如果是同一个对象的引用,则直接返回true;

    如果地址不一样,则证明不是引用同一个对象,接下来就是挨个去比较两个字符串对象的内容是否一致,完全相等返回true,否则false。

    hashCode

    
    
    /** The value is used for character storage. */
    private final char value[];

    private int hash;// Default to 0
    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; }

    hashcode方法返回该对象的哈希码值。

    如果根据 equals(Object) 方法,两个对象是相等的,那么在两个对象中的每个对象上调用 hashCode 方法都必须生成相同的整数结果。

  • 相关阅读:
    hdu 5352 匈牙利(多重匹配)
    hdu 2112 最短路+stl
    hdu 1811 拓扑排序+并查集+细心
    hdu5407 CRB and Candies
    hdu1018 Big Number
    hdu5410 CRB and His Birthday
    hdu1023 Train Problem II
    hdu4812 D Tree
    hdu1085 Holding Bin-Laden Captive!
    hdu4810 Wall Painting
  • 原文地址:https://www.cnblogs.com/gczmn/p/10411094.html
Copyright © 2011-2022 走看看