-6

I am trying to break the rule of set by allowing the same object to be twice (just for fun)

This is my code:

class Person implements Comparable<Person> {
    public String firstName;

    public Person(String firstName) {
        this.firstName = firstName;
    }

    @Override
    public int compareTo(Person o) {
        return 4;
    }
}

class customTreeSet<T extends Person> extends TreeSet<T> {

    private static final long serialVersionUID = 1L;

}

and I call it like this:

Set<Person> set = new customTreeSet<Person>();
        set.add(new Person("Forza"));
        set.add(new Person("Forza"));
        for (Person person : set) {
            System.out.println(person.firstName);
        }

what I am facing is that when i leave the return as 4, my set contains two objects, but when i change it to zero my set contains one object.

i need to know the rule for the returning type specially that it is integer not boolean, if it was boolean, i will say that true means two objects are the same, false means not, but here it is an integer value not boolean.

thanks for your help

Marco Dinatsoli
  • 10,322
  • 37
  • 139
  • 253
  • 7
    http://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html#compareTo-T- tl;dr: it returns 0 for equal objects. – Marvin Oct 27 '15 at 20:52
  • 1
    you need to cheat with the equals() and hashCode() methods. You also need to get out more. – NickJ Oct 27 '15 at 21:06

1 Answers1

2

The Comparable interface is used to compare two objects and their order. As per the Javadocs, the compareTo method should return 0 if the two objects are equal, any negative number if this object is "smaller" than the specified other, and any positive number if this object is "larger" than the specified other. What "smaller" and "larger" means is entirely dependent on what you're trying to model - for Strings, for example, "greater than" and "less than" refer to their alphabetic ordering, while for Integers it refers to their natural ordering.

In your case, by always returning 4, you're claiming that 1) the objects are not equal, and 2) both objects are larger than the other (which doesn't really make sense semantically, but if it works for you, whatever).

Mage Xy
  • 1,803
  • 30
  • 36