Demo - The equals Method and Hash -Person Class

package ClassEqualDemo; //Person Class - Demo of Equal and hash import java.util.Objects; public class Person { //variables************** private String firstName; private String lastName; private int age; //Constructor public Person(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } // Getters and Setters public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } //Override Functions @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return age == person.age && Objects.equals(firstName, person.firstName) && Objects.equals(lastName, person.lastName); } @Override public int hashCode() { return Objects.hash(firstName, lastName, age); } }

Driver:

package ClassEqualDemo; public class ClassEqualDriver { public static void main(String[] args) { //create some Persons Person personOne = new Person("Kevin", "Roark", 29); Person personTwo = new Person("Fred", "Flintstone", 39); Person personThree = new Person("Kevin", "Roark", 29); //Now find out if they are equal System.out.println("Is personOne equal to personTwo:"); if(personOne.equals(personTwo)) { System.out.println("The objects are equal"); } else { System.out.println("The objects are NOT equal"); } System.out.println("Is personOne equal to personThree:"); if(personOne.equals(personThree)) { System.out.println("The objects are equal"); } else { System.out.println("The objects are NOT equal"); } //now print out the Hash values System.out.println("The Hash values for each object are:"); System.out.println("personOne: " + personOne.hashCode()); System.out.println("personTwo: " + personTwo.hashCode()); System.out.println("personThree: " + personThree.hashCode()); } }

 

COSC-1437 / ITSE-2457 Computer Science Dept. - Author: Dr. Kevin Roark