fork download
  1. import java.util.List;
  2. import java.util.Objects;
  3. import java.util.TreeSet;
  4.  
  5. class Scratch {
  6. public static void main(String[] args) {
  7. Foo fooOne = Foo.of(1);
  8. Foo fooTwo = Foo.of(2);
  9. Foo fooThree = Foo.of(3);
  10. TreeSet<Foo> set = new TreeSet<>();
  11. set.addAll(List.of(fooOne, fooTwo, fooThree));
  12. System.out.println(set.size());
  13. fooOne.setValue(4);
  14. set.add(fooOne);
  15. System.out.println(set.size());
  16. }
  17. }
  18.  
  19. class Foo implements Comparable<Foo> {
  20. private int value;
  21.  
  22. private Foo(int value) {
  23. this.setValue(value);
  24. }
  25.  
  26. public static Foo of(int value) {
  27. return new Foo(value);
  28. }
  29.  
  30. public int getValue() {
  31. return value;
  32. }
  33.  
  34. public Foo setValue(int value) {
  35. this.value = value;
  36. return this;
  37. }
  38.  
  39. @Override
  40. public boolean equals(Object o) {
  41. if (this == o) {
  42. return true;
  43. }
  44. if (o == null || getClass() != o.getClass()) {
  45. return false;
  46. }
  47. Foo foo = (Foo) o;
  48. return getValue() == foo.getValue();
  49. }
  50.  
  51. @Override
  52. public int hashCode() {
  53. return Objects.hash(value);
  54. }
  55.  
  56. @Override
  57. public int compareTo(Foo that) {
  58. return getValue() - that.getValue();
  59. }
  60. }
Success #stdin #stdout 0.06s 32800KB
stdin
Standard input is empty
stdout
3
4