Java 一个ArrayList与另一个ArrayList的差异同步(添加、删除但不覆盖)

Java 一个ArrayList与另一个ArrayList的差异同步(添加、删除但不覆盖),java,arraylist,Java,Arraylist,新数据: ArrayList<Comment> newComments = getComments(); ArrayList newComments=getComments(); 已存在数据,已填写一些数据: ArrayList<Comment> oldComments ArrayList oldComments 我不能用新内容覆盖整个旧内容 我希望newComments中的新对象(尚未出现)Comment添加到oldcoments,同时我希望newComme

新数据:

ArrayList<Comment> newComments =  getComments();
ArrayList newComments=getComments();
已存在数据,已填写一些数据:

ArrayList<Comment> oldComments 
ArrayList oldComments
我不能用新内容覆盖整个旧内容

我希望
newComments
中的新对象(尚未出现)
Comment
添加到
oldcoments
,同时我希望
newComments
中缺少的对象从
oldcoments
中删除

Collections
package中有什么好的方法吗?还是其他方式

注:<代码>注释< /Cord>类具有自定义<代码> COMPARE()/>代码>方法(不使用默认代码>
请注意,您需要确保
Comment
类重写
equals()
方法,以确保两个列表有效地并集而不是串联。

A
java.util.Set
更适合您的用例。然后你可以做:

oldComments.retainAll(newComments);
oldComments.addAll(newComments);

操作后,
oldComments
将与
newComments
相同?只有在
newComments
没有与
oldComments
中类似的项(
compare()
方法为true)的情况下。对不起,混淆了,我的意思是它们的内容将是相同的,即
compare()
将为这两个参数返回
true
。您已经找到了一个令人满意的答案,但能否澄清您不能“用新内容覆盖整个旧内容”?@Miseraverable Yes
Compare()
将返回true
Compare()
只比较
Comment
对象的title和author属性,而不是整个内容。例如,我们在Stackoverflow上编写的这些注释,假设您正在编辑一条注释,也希望注释部分自动刷新。刷新时,用户添加的新注释将显示,其他用户删除的注释不应再出现在此处,并且您正在编辑的内容不应被覆盖。谢谢,我需要实现自定义
equals()
hashcode()
union
将保留旧版本中不在新版本中的条目,OP希望他们被移除。