zoukankan      html  css  js  c++  java
  • String的equals和hashCode方法

    对于判断对象是否相等,肯定需要重写它的equals和hashCode方法。不然使用默认的方法只会比较地址,因此会出现错误。

    以String类为例,且看它的equals方法

        public boolean equals(Object anObject) {
        //比较地址
        if (this == anObject) {
            return true;
        }
        //看是否是String实例
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = count;
            //比较字符串长度
            if (n == anotherString.count) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = offset;
            int j = anotherString.offset;
            while (n-- != 0) {
                //比较字符是否相等
                if (v1[i++] != v2[j++])
                return false;
            }
            return true;
            }
        }
        return false;
        }          

    主要思想:比较地址、比较长度、比较字符

    hsahCode实现方式:

        public int hashCode() {
        int h = hash;
            int len = count;
        if (h == 0 && len > 0) {
            int off = offset;
            char val[] = value;
    
                for (int i = 0; i < len; i++) {
                    h = 31*h + val[off++];
                }
                hash = h;
            }
            return h;
        }
  • 相关阅读:
    P1308 统计单词数(cin,getline() ,transform() )
    解决ASP.NET中的各种乱码问题
    GUID
    c# Thread、ThreadPool、Task的区别
    线程学习参考
    异步
    Lamda简单使用
    ubuntu上安装docker
    Git设置ssh密钥
    Git客户端(TortoiseGit)基本使用详解
  • 原文地址:https://www.cnblogs.com/lidedong/p/9900033.html
Copyright © 2011-2022 走看看