Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Tutorial 41 The Equals Method
- //pretty easy straight forward stuff
- class Person {
- private int id;
- private String name;
- public Person(int id, String name) { //rightclick>source>generate constructor using fields>check all fields you want>delete "super()"
- this.id = id;
- this.name = name;
- }
- @Override
- public String toString() { //rightclick>source>generate toString>click the fields you want
- return "Person [id=" + id + ", name=" + name + "]";
- }
- @Override
- public int hashCode() { //to generate .equals method, rightclick>source>hashCode()andequals()>check the fields you want to compare
- final int prime = 31;
- int result = 1;
- result = prime * result + id;
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Person other = (Person) obj;
- if (id != other.id)
- return false;
- if (name == null) {
- if (other.name != null)
- return false;
- } else if (!name.equals(other.name))
- return false;
- return true;
- }
- }
- public class App {
- public static void main(String[] args) {
- Person person1 = new Person(5, "Bob");
- Person person2 = new Person(5, "Bob");
- person2 = person1;
- System.out.println(person1.equals(person2)); //.equalS to tell if values are equal
- }
- }
- //---------------------------------------------------------------------------------------------------------------------------------------
- /* Run Results:
- True
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement