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

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值