fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10.  
  11.  
  12. public static void main(String[] args){
  13. Set<Name> s = new HashSet<Name>();
  14. Name n1 = new Name("Donald", "Duck");
  15. Name n2 = new Name("Donald", "Duck");
  16. s.add(n1);
  17.  
  18. System.out.print("HashCodes equal: ");
  19. System.out.println( n1.hashCode() == n2.hashCode());
  20. System.out.print("Objects equal: ");
  21. System.out.println( n1.equals(n2) );
  22.  
  23. System.out.print("HashSet contains n1: ");
  24. System.out.println(s.contains(n1));
  25.  
  26. System.out.print("HashSet contains n2: ");
  27. System.out.println(s.contains(n2));
  28. }
  29. }
  30. class Name {
  31. private String first, last;
  32.  
  33. public Name(String first, String last){
  34. this.first = first;
  35. this.last = last;
  36. }
  37.  
  38. @Override
  39. public boolean equals(Object o){
  40. Name n = (Name)o;
  41. return n.first.equals(first) && n.last.equals(last);
  42. }
  43.  
  44. public int hashCode(){
  45. return 31*first.hashCode()+last.hashCode();
  46. }
  47.  
  48. }
Success #stdin #stdout 0.07s 381184KB
stdin
Standard input is empty
stdout
HashCodes equal: true
Objects equal: true
HashSet contains n1: true
HashSet contains n2: true