Guest User

Untitled

a guest
Jun 22nd, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. int id, String name ,String surname,int age -- with getters and setters
  2.  
  3. List <Person> persons = new ArrayList<Person>();
  4.  
  5. package stackoverflow.q_24935480;
  6.  
  7. import java.util.HashSet;
  8. import java.util.Set;
  9.  
  10. public class TestPersonInSet {
  11. public static void main(String[] args) {
  12. Set<Person> s = new HashSet<Person>();
  13. Person p1 = new Person(); p1.setName("abc");
  14. Person p2 = new Person(); p2.setName("abc");
  15. s.add(p1);
  16. s.add(p2);
  17. System.out.println("Set size is " + s.size());
  18. }
  19.  
  20. static class Person {
  21. private String name;
  22.  
  23. public void setName(String name) {
  24. this.name = name;
  25. }
  26.  
  27. @Override
  28. public int hashCode() {
  29. final int prime = 31;
  30. int result = 1;
  31. result = prime * result + ((name == null) ? 0 : name.hashCode());
  32. return result;
  33. }
  34.  
  35. @Override
  36. public boolean equals(Object obj) {
  37. if (this == obj)
  38. return true;
  39. if (obj == null)
  40. return false;
  41. if (getClass() != obj.getClass())
  42. return false;
  43. Person other = (Person) obj;
  44. if (name == null) {
  45. if (other.name != null)
  46. return false;
  47. } else if (!name.equals(other.name))
  48. return false;
  49. return true;
  50. }
  51.  
  52. }
  53. }
  54.  
  55. //Output:
  56. //Set size is 1
Add Comment
Please, Sign In to add comment