fork(2) download
  1. import java.util.*;
  2. import java.lang.*;
  3.  
  4. class Main
  5. {
  6. static class Person {
  7. private String first;
  8. private String last;
  9. public String getFirst() {return first;}
  10. public String getLast() {return last;}
  11. public Person(String f, String l) {
  12. first = f;
  13. last = l;
  14. }
  15. public String toString() {
  16. return first+" "+last;
  17. }
  18. }
  19. public static void main (String[] args) throws java.lang.Exception
  20. {
  21. List<Person> people = new ArrayList<Person>();
  22. people.add(new Person("John", "Smith"));
  23. people.add(new Person("John", "Scott"));
  24. people.add(new Person("Jack", "First"));
  25. people.add(new Person("John", "Walker"));
  26. people.add(new Person("Jack", "Black"));
  27. Set<Object> seen = new HashSet<Object>();
  28. for (Person p : people) {
  29. final Person thisPerson = p;
  30. class Wrap {
  31. public int hashCode() { return thisPerson.getFirst().hashCode(); }
  32. public boolean equals(Object o) {
  33. Wrap other = (Wrap)o;
  34. return other.wrapped().getFirst().equals(thisPerson.getFirst());
  35. }
  36. public Person wrapped() { return thisPerson; }
  37. };
  38. Wrap wrap = new Wrap();
  39. if (seen.add(wrap)) {
  40. System.out.println(p + " is new");
  41. } else {
  42. System.out.println(p + " is a duplicate");
  43. }
  44. }
  45. }
  46. }
Success #stdin #stdout 0.03s 245632KB
stdin
Standard input is empty
stdout
John Smith is new
John Scott is a duplicate
Jack First is new
John Walker is a duplicate
Jack Black is a duplicate