Can't delete an object from a set

113 views Asked by At

I need to delete a comment from a Set<Commentaries>. And it worked! But I try with the code below, it doesn't work. After I ordered my Set by using a TreeSet with MyComparator

@RequestMapping("/user/editPage/{idContractor}")
public String goToEditPage(@PathVariable("idContractor") Integer idContractor, Model model) {

.....

Set<Commentaries> comSet = contractorsWithId.getCommentarieses();
TreeSet<Commentaries> treeComment = new TreeSet<Commentaries>(new MyComparator());
treeComment.addAll(comSet);
contractorsWithId.setCommentarieses(treeComment);

return "user/editPage";
}

//Below my method for delete

public void removeCommentaries(Commentaries commentToDelete, Contractors contractorWithID) {
    contractorWithID.getCommentarieses().remove(commentToDelete);
    contractorsService.update(contractorWithID);
}

Help me please! I'm new to stackoverflow and if something you don't understand I can edit my question!

2

There are 2 answers

0
Gopinath Langote On
  • while working with TreeSet make sure your Comparator gives a correct result.
  • In your case MyComparator comparing on which field is important.
  • If Comparator return 0 means two comments are same which will not be added to treeset while doing treeComment.addAll(comSet);
  • If comment not gets added to treeset which mean you can't remove it.
  • though all collections gives you return flag on remove check that. If it is false means that comment was not present in treeset.

The problem with specific code will help.

0
Ilya On

I have creates simple example, but it works. Please, correct me:

public class Main
{
   static Contractors con = new Contractors();

   static Commentaries com = new Commentaries("TROL");

   static
   {
      con.getCommentarieses().add(new Commentaries("1A"));
      con.getCommentarieses().add(new Commentaries("2B"));
      con.getCommentarieses().add(com);
      con.getCommentarieses().add(new Commentaries("3C"));
   }

   public static void main(String[] args)
   {
      Set<Commentaries> comSet = con.getCommentarieses();
      TreeSet<Commentaries> treeComment = new TreeSet<>((a1, a2) -> {return a1.name.compareTo(a2.name);});
      treeComment.addAll(comSet);
      con.setCommentarieses(treeComment);

      removeCommentaries(com, con);

      System.out.println(con);
   }

   public static void removeCommentaries(Commentaries commentToDelete, Contractors contractorWithID) 
   {
      contractorWithID.getCommentarieses().remove(commentToDelete);
   }
}

Object is removed like expected