026_使用eclipse生成hashCode和equals方法
生活随笔
收集整理的这篇文章主要介绍了
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方法*/@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + id;return result;}/*** eclipse功能生成equals方法*/@Overridepublic 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方法*/@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + id;return result;}/*** eclipse功能生成equals方法*/@Overridepublic 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返回falseSystem.out.println(xiaoming.equals(xiaocui));} }1.4. 输出:
xiaocui hashCode = 9032 xiaocui hashCode = 9032
false
总结
以上是生活随笔为你收集整理的026_使用eclipse生成hashCode和equals方法的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 025_JDK的hashCode方法
- 下一篇: 027_自己实现一个ArrayList