026_使用eclipse生成hashCode和equals方法

本文通过一个具体的Java代码示例,展示了两个不同对象(People和Student)由于只基于id属性生成hashCode,导致它们的hashCode相同,但equals方法返回false的情况。这说明在实现equals和hashCode方法时应确保一致性和正确性,以避免哈希表中的不期望行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 使用eclipse生成hashCode方法, 模拟一个两个对象实例不同, hashCode形同, 两个对象的equals方法返回flase的场景。

1.1. People类

public class People {
	int id;
	String name;
	int age;

	public People(int id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}

	/**
	 * eclipse功能生成hashCode方法
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		return result;
	}

	/**
	 * eclipse功能生成equals方法
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		People other = (People) obj;
		if (id != other.id)
			return false;
		return true;
	}

}

1.2. Student类

public class Student {
	 int id;
	 String name;
	 int age;
	
	public Student(int id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}
	
	/**
	 * eclipse功能生成hashCode方法
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		return result;
	}
	
	/**
	 * eclipse功能生成equals方法
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (id != other.id)
			return false;
		return true;
	}
	
}

1.3. MyHashCode类

public class MyHashCode {
	public static void main(String[] args) {
		People xiaoming = new People(9001, "xiaoming", 22);
		Student xiaocui = new Student(9001, "xiaocui", 16);

		// 对象不同, hashCode相等
		System.out.println("xiaocui hashCode = " + xiaoming.hashCode() + " xiaocui hashCode = " + xiaocui.hashCode());
		// 对象不同, hashCode相等, 两个对象的equals返回false
		System.out.println(xiaoming.equals(xiaocui));
	}
}

1.4. 输出:

xiaocui hashCode = 9032 xiaocui hashCode = 9032

false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值