Created
December 16, 2015 15:52
-
-
Save AnnaBoro/688cd993e18519f02dc9 to your computer and use it in GitHub Desktop.
overriding hashcode() and equals()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package lesson7.hashcodeoverriding; | |
public class Launcher { | |
public static void main(String[] args) { | |
Person p1 = new Person(); | |
Person p2 = new Person(); | |
p1.setName("Ivan"); | |
p1.setAge(22); | |
p1.setSalary(2222); | |
p2.setName("erw"); | |
p2.setAge(22); | |
p2.setSalary(2222); | |
System.out.println(p1.hashCode()); | |
System.out.println(p2.hashCode()); | |
System.out.println(p1.equals(p2)); | |
System.out.println(p2.equals(p1)); | |
p2.setName("Ivan"); | |
System.out.println(p1.hashCode()); | |
System.out.println(p2.hashCode()); | |
System.out.println(p1.equals(p2)); | |
System.out.println(p2.equals(p1)); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package lesson7.hashcodeoverriding; | |
public class Person { | |
private String name; | |
private int age; | |
private long salary; | |
public Person() { | |
} | |
@Override | |
public int hashCode() { | |
final int prime = 8; | |
int c = name.hashCode(); | |
int result = 1; | |
result = prime * result + c; | |
c = ((Integer)age).hashCode(); | |
result = prime * result + c; | |
c = ((Long)salary).hashCode(); | |
result = prime * result + c; | |
return result; | |
} | |
@Override | |
public boolean equals(Object obj) { | |
Person person = (Person) obj; | |
return getName().equals(person.getName()) && (getAge() == person.getAge()) && (getSalary() == person.getSalary()); | |
} | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
public int getAge() { | |
return age; | |
} | |
public void setAge(int age) { | |
this.age = age; | |
} | |
public long getSalary() { | |
return salary; | |
} | |
public void setSalary(long salary) { | |
this.salary = salary; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment