我需要删除Set<Commentaries>
的评论。它奏效了!但我尝试使用下面的代码,它不起作用。
我使用Set
和TreeSet
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";
}
//在我的删除方法
下面public void removeCommentaries(Commentaries commentToDelete, Contractors contractorWithID) {
contractorWithID.getCommentarieses().remove(commentToDelete);
contractorsService.update(contractorWithID);
}
请帮帮我!我是stackoverflow的新手,如果你不明白我可以编辑我的问题!
答案 0 :(得分:0)
我创建了一个简单的例子,但它有效。请纠正我:
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);
}
}
对象被移除,如预期的
答案 1 :(得分:0)
MyComparator
比较哪个字段很重要。treeComment.addAll(comSet);
特定代码的问题会有所帮助。