Java中详述HashSet类add方法(二)

当在Java的HashSet中使用add方法添加重复元素时,返回false。关键在于hashCode方法,不同对象若重写hashCode返回相同值,会导致冲突。在HashMap的putVal过程中,因相同hashCode导致的冲突会使第二次添加失败,返回第一次存储的数据地址,从而返回false。
摘要由CSDN通过智能技术生成

hashCode方法

当使用HashSet中的add方法添加重复数据时,返回值为false,欲分析底层源代码,需要进行对HashCode方法进行分析说明。

public class Test1 {
   
	  
	  static final int hash(Object key) {
   //在源代码中摘出hash方法进行分析操作。
	        int h;
	        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
	    }

	  public static void main(String[] args) {
   
	    
	      Integer a = 11;
	      Integer b = new Integer(11);
	      System.out.println(hash(a));
	      System.out.println(hash(b));
	    
	      String str1="11111";
	      String str2=new String("11111");
	      System.out.println(hash(str1));
	      System.out.println(hash(str2));
	    	      
	      Student stu1 = new Student();
	      Student stu2 = new Student();
	      System.out.println(hash(stu1));
	      System.out.println(hash(stu2));
	  }
}
结果为:
11
11
46760248
46760248
5433712
2430314
public class Student {
   

}

从代码中我们可以发现当为重写HashCode方法时,不同的对象调用Hashcode方法返回值是不一样的,下面我们重写Student类中的HashCode方法:

public class Student {
   

	@Override
	public int hashCode() {
   
		return 0;
	}	
}
Test1中代码结果为:
11
11
46760248
46760248
0
0

可推出结论:
同一个对象调用多次该方法,结果相同;不同对象,如果重写了hashCode方法,使得其返回值相同,则多次调用该方法,结果相同;这个结论在后面分析代码时会起到决定性作用。

对象名.add方法添加元素,元素重复

import java.util.HashSet;

public class Test2 {
   

	public static void main(String
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值