欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA equals方法重写时要重写hashCode方法

程序员文章站 2022-05-20 12:20:55
...
package test;

import java.util.HashSet;
import java.util.Set;

/** 
 * @author qxch0372@163.com
 */
public class Test1
{
	
	public static void main(String[] args) {
		Set<Student> set = new HashSet<Student>();
		Student s1 = new Student("ZhangSan", 13);
		Student s2 = new Student("ZhangSan", 13);
		System.out.println(s1.hashCode());
		System.out.println(s2.hashCode());
		set.add(s1);
		set.add(s2);
		System.out.println(set);
		System.out.println(s1.equals(s2));
	}
	
}

class Student {
	private String name;
	private Integer age;
	public Student(String name, Integer age) {
		this.name = name;
		this.age = age;
	}
	
	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}
	
	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String toString() {
		return name + "'s age is " + String.valueOf(age);
	}
	
	public boolean equals(Object other) {
		if(this == other)
			return true;
		if(other == null)
			return false;
		if(!(other instanceof Student))
			return false;
		
		final Student stu = (Student)other;
		if(!getName().equals(stu.getName())) 
			return false;
		if(!getAge().equals(stu.getAge()))
			return false;
		return true;
	}
	
	public int hashCode() {
		int result = getName().hashCode();
		result = 29*result + getAge().hashCode();
		return result;
	}
	
}

   在重写equals方法的时候一定要重写hashCode()方法

相关标签: equals 重写