0

I am trying to insert multiple objects in a TreeSet . The problem is one object inserts fine, but when I insert second object and tries to view both objects, I get the second object twice. How can I prevent my old values from getting replaced..

This is my POJO

    public Class Question implements Comparable<Question>
    {
     .....
     public int compareTo(Question q) {
    if(vote>q.vote)
        return -1;
    else
        return 1;
}

And this is the function which inserts object into the treeSet

public void save(String ques, String sessionId, Question question)
{
question.setQuesId(++quesId);                  
question.setQues(ques);
question.setSessionId(sessionId);
question.setVote(0);
setDemo.add(Question);
}

Note: "setDemo" is my treeSet object

Any advices are appreciated. Thankyou

jbx
  • 21,365
  • 18
  • 90
  • 144
Himanshu Arya
  • 75
  • 1
  • 9

1 Answers1

1

First of all, your comparator should handle the case in which the votes are equal.

public int compareTo(Question q) {
    if(vote>q.vote) {
        return -1;
    } else if (vote<q.vote){
        return 1;
    } else {
        return 0;
    }
}

Secondly, make sure you override equals properly in Question.

If both the compareTo method returns 0 and the equals returns true, TreeSet will override your value, since it will detect the two values as duplicates. Otherwise, you should not get any replacements.

Although TreeSet does not use hashCode internally, I would suggest overriding that as well, since you might want to change the implementation from TreeSet to HashSet in the future.

  • My business logic does not require me to check the equal condition as all votes initially be at 0. – Himanshu Arya Sep 21 '18 at 09:09
  • 2
    Your business logic might not, but the javadoc for compareTo assumes that you would. Here it is `@return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.`. `TreeSet` assumes that you are respecting the contract of `compareTo`, and only in that scenario it will behave as expected. –  Sep 21 '18 at 09:12
  • If you want to be able to use your TreeSet for just about anything, you need to handle the equality case correctly. – Louis Wasserman Sep 21 '18 at 16:35