fork(1) download
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. class Experiment {
  5. public static void main(String args[]) {
  6. Student s1 = new Student("uvw");
  7. Student s2 = new Student("xyz");
  8. HashSet<Student> set = new HashSet<>();
  9. set.add(s1);
  10. set.add(s2);
  11. System.out.println(set);
  12.  
  13. Student s3 = new Student("uvw");
  14.  
  15. System.out.println("s3 equals s1 ? " + s1.equals(s3));
  16. System.out.println("s1 hash = " + s1.hashCode());
  17. System.out.println("s3 hash = " + s3.hashCode());
  18.  
  19. System.out.println( set.contains(s3) );
  20. }
  21. }
  22. class Student{
  23.  
  24. String name;
  25.  
  26. public Student(String name) {this.name=name;}
  27.  
  28. /* @Override
  29.   public int hashCode() {
  30.   return name.length();
  31.   }*/
  32.  
  33. @Override
  34. public boolean equals(Object obj) {
  35. if (name.equals( ((Student)obj).name ))
  36. return true;
  37. return false;
  38. }
  39.  
  40. @Override
  41. public String toString() {
  42. return "Student{" +
  43. "name='" + name + '\'' +
  44. '}';
  45. }
  46. }
Success #stdin #stdout 0.04s 4386816KB
stdin
Standard input is empty
stdout
[Student{name='uvw'}, Student{name='xyz'}]
s3 equals s1 ? true
s1 hash = 1735600054
s3 hash = 2133927002
false