hashcode 比较

1 Object方法中有这样两个方法 hashcode equals 用来比较对象

   原则 1, == 只判断两个对象引用值是否相等

           Student stu1 = new Student();

           Student stu2 = new Student();

           Student stu3 = stu1 

               则 stu1 == stu2  false 

                  stu1 == stu2  true

        2, equals 先判断hashCode(默认为内存地址)是否相等 后判断 equals 是否相等

             如果hashCode 不相等 则在用equals 比较时 一定不会相等 因为 equals 比较结果是建立在  hashCode 结果之上的 可以理解为并的效果(只是这么理解)

              引申结果:hashCode 不等 则equals一定不等 只有  hashCode 相等 也不一定相等 只有两者同时满足时 才相等 

              所以一般自定义类时 当我们重写equals方法是 都习惯的去重写hashCode方法 但不是必须

默认这些方法都是继承于Object

 

 

 

package com.gui.test;

class Student{

 int num;

 String name;

 Student(int num,String name){

             this.num=num;

             this.name=name; }

 public int hashCode(){ //重写hashCode的方法

             return num*name.hashCode(); }

 public boolean equals(Object o) {

             Student s=(Student)o;

             return true; //&&的优先级比==低,所以前面不必加括号

 }

 public String toString(){return num+":"+name; }

 }


 

 

package com.gui.test;

import java.util.HashSet;

public class HashSetTest {

 public static void main(String[] args) {

  HashSet<Student> hs = new HashSet<Student>();

  hs.add(new Student(1, "zhangsan"));

  hs.add(new Student(2, "lisi"));

  hs.add(new Student(3, "wangwu"));

  hs.add(new Student(1, "zhangsan"));

  for (Student stu : hs) {
   System.out.println(stu.toString());
  }
  
  Student stu1 = new Student(2,"gui");
  Student stu2 = new Student(2,"gui");
  Student stu3 = stu1;
  
  if(stu1 == stu2) System.out.println(" stu1 == stu2 ");// false
  if(stu1 == stu3) System.out.println(" stu1 == stu3 ");//true
  if(stu1.equals(stu2)) System.out.println(" stu1.equals(stu2) "); //true
  
  
 }
 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值