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