Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int id, String name ,String surname,int age -- with getters and setters
- List <Person> persons = new ArrayList<Person>();
- package stackoverflow.q_24935480;
- import java.util.HashSet;
- import java.util.Set;
- public class TestPersonInSet {
- public static void main(String[] args) {
- Set<Person> s = new HashSet<Person>();
- Person p1 = new Person(); p1.setName("abc");
- Person p2 = new Person(); p2.setName("abc");
- s.add(p1);
- s.add(p2);
- System.out.println("Set size is " + s.size());
- }
- static class Person {
- private String name;
- public void setName(String name) {
- this.name = name;
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- 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 (name == null) {
- if (other.name != null)
- return false;
- } else if (!name.equals(other.name))
- return false;
- return true;
- }
- }
- }
- //Output:
- //Set size is 1
Add Comment
Please, Sign In to add comment