hashCode()方法和equal()方法

1  equals:
        如果不重写,则调用的Object的equals方法,Object.equals方法运用的‘==’,比较的是内存地址;
        String的equals方法,已经被重写,比较的是字符串内的字符。
        equals简单重写:1为空 false;  2== 为 ture ;3类比较,且属性值相等 true
            public boolean equals(Object obj) {
                if(obj==null)
                return false;
                if(this == obj){
                    return true;
                }
                if (getClass() != obj.getClass())  
                   return false;  
               User other = (User) obj;  
               if (name == null) {  
                   if (other.name != null)  
                       return false;  
               } else if (!name.equals(other.name))  
                   return false;  
               return true;  
            }
2    ==:
        比较的是内存地址
         String s1 = "nihao";
         String s2 = "nihao";
         String s3 = new String("nihao");
         System.out.println(s1 == s2);    //    true
         System.out.println(s1 == s3);    //    false
         说明:s1和s2都是字符串字面值“nihao”的引用,指向同一块地址;s3通过new产生的对象在堆中,s3是堆中变量的引用,地址不同。
3    hashCode:
        hashCode值是一种算法,是根类Obeject中的方法,如果不重写,默认返回对象32位jvm内存地址,
        String类源码中重写的hashCode方法:
            public int hashCode() {
                 int h = hash;    //Default to 0 ### String类中的私有变量,
                 if (h == 0 && value.length > 0) {    //private final char value[]; ### Sting类中保存的字符串内容的的数组,因此String是不可变的。
                     char val[] = value;
            
                     for (int i = 0; i < value.length; i++) {
                         h = 31 * h + val[i];
                     }
                     hash = h;
                 }
                 return h;
             }

猜你喜欢

转载自blog.csdn.net/alenejinping/article/details/85119837