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