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

    为什么要有 hashCode引用
    我们以“HashSet 如何检查重复”为例子来说明为什么要有 hashCode:

    当你把对象加入 HashSet 时,HashSet 会先计算对象的 hashcode 值来判断对象加入的位置,同时也会与其他已经加入的对象的 hashcode 值作比较,如果没有相符的hashcode,HashSet会假设对象没有重复出现。但是如果发现有相同 hashcode 值的对象,这时会调用 equals()方法来检查 hashcode 相等的对象是否真的相同。如果两者相同,HashSet 就不会让其加入操作成功。如果不同的话,就会重新散列到其他位置。这样我们就大大减少了 equals 的次数,相应就大大提高了执行速度。

    hashCode()与equals()的相关规定
    如果两个对象相等,则hashcode一定也是相同的
    两个对象相等,对两个对象分别调用equals方法都返回true
    两个对象有相同的hashcode值,它们也不一定是相等的
    因此,equals 方法被覆盖过,则 hashCode 方法也必须被覆盖
    hashCode() 的默认行为是对堆上的对象产生独特值。如果没有重写 hashCode(),则该 class 的两个对象无论如何都不会相等(即使这两个对象指向相同的数据)

    所以,在向HashSet中存放自定义类型对象时,一定要重写hashCode和equals方法

    package set_map;
    
    public class Person {
    	private String name;
    	private int age;
    	private String sex;
    	
    	
    	
    	public Person(String name, int age) {
    		super();
    		this.name = name;
    		this.age = age;
    	}
    	
    	public Person(String name, int age, String sex) {
    		super();
    		this.name = name;
    		this.age = age;
    		this.sex = sex;
    	}
    
    	@Override
    	public int hashCode() {
    		final int prime = 31;
    		int result = 1;
    		result = prime * result + age;
    		result = prime * result + ((name == null) ? 0 : name.hashCode());
    		result = prime * result + ((sex == null) ? 0 : sex.hashCode());
    		return result;
    	}
    
    	@Override // 重写equals
    	public boolean equals(Object obj) {
    		if (this == obj)
    			return true;
    		if (obj == null)
    			return false;
    		if (!(obj instanceof Person))
    			return false;
    		Person other = (Person) obj;// 防止向上转型出现
    		if (age != other.age)
    			return false;
    		if (name == null) { // null不能使用equals方法
    			if (other.name != null)
    				return false;
    		} else if (!name.equals(other.name))
    			return false;
    		if (sex == null) {
    			if (other.sex != null)
    				return false;
    		} else if (!sex.equals(other.sex))
    			return false;
    		
    		return true;	
    	}
    	
    }
    
  • 相关阅读:
    matplotlib数据可视化之柱形图
    xpath排坑记
    Leetcode 100. 相同的树
    Leetcode 173. 二叉搜索树迭代器
    Leetcode 199. 二叉树的右视图
    Leetcode 102. 二叉树的层次遍历
    Leetcode 96. 不同的二叉搜索树
    Leetcode 700. 二叉搜索树中的搜索
    Leetcode 2. Add Two Numbers
    Leetcode 235. Lowest Common Ancestor of a Binary Search Tree
  • 原文地址:https://www.cnblogs.com/zhz-8919/p/10697030.html
Copyright © 2011-2022 走看看