My Treeset only adds 1 class object

后端 未结 3 1869
你的背包
你的背包 2021-01-27 07:08

I\'m trying to add the below book objects to a TreeSet. However, when I debug the code, it says that the set has a size of 1 and only contains the first object added (book1). Wh

相关标签:
3条回答
  • 2021-01-27 07:37

    Update your compareTo method based on your requirement. Or at least update as below, it will allow to insert all objects in treeset.

    public int compareTo(Book o) {
    // TODO Auto-generated method stub
    return this.compareTo(o);
    } 
    
    0 讨论(0)
  • 2021-01-27 07:44
    @Override
    public int compareTo(Book o) {
        // TODO Auto-generated method stub
        return 0;
    }
    

    What Comparable#compareTo return value says -

    a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. documentation

    When you added multiple object to tree set, a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal.All the object are equals by Book objects compareTo method(provided) definition, so TreeSet just ignored duplicate object.

    Solution: Define compareTo method correctly, keeping this thing in mind return value should negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

    0 讨论(0)
  • 2021-01-27 07:50

    All books are equal to one another (evident by returning 0). A Set cannot contain duplicates, so that's why only one (the first Book) is ever added

    @Override
    public int compareTo(Book o) {
        // TODO Auto-generated method stub
        return 0;
    }  
    

    You need to fill in the details of the method. Negative numbers say this book is less than o, vice versa for positive numbers

    0 讨论(0)
提交回复
热议问题