【问题标题】:Compare two list common data,new data and old data比较两个列表常用数据,新数据和旧数据
【发布时间】:2017-03-21 14:26:50
【问题描述】:

您好,我有两个列表示例 List list1 和 LIST List list2

如何获取常用数据? 数据仅在第一个列表中吗? 数据只在第二个列表中?

由于我使用的是 List 是否需要覆盖 equals 和 hashcode 方法?

请您提供示例示例。

【问题讨论】:

  • 向我们展示您到目前为止所尝试的内容,您的代码。
  • Java Compare Two Lists的可能重复
  • 您关心订购吗?列表 [A,B] 和 [B,A] 是否不同? [B,C] 和 [A,B,C] 之间有多少区别?如果您的答案是“否”且“只有 A”,那么您对集合而不是列表之间的差异感兴趣,这要容易得多 - 请在这种情况下重新表述您的问题。

标签: java arraylist collections


【解决方案1】:
ArrayList onlyInList1 = new ArrayList(list1);
onlyInList1.removeAll(list2);

ArrayList onlyInList2 = new ArrayList(list2)
list2.removeAll(list1);

ArrayList inBoth = new ArrayList(list1)
inBoth.retainAll(list2);

【讨论】:

  • 如果 list1 包含列表 bean 意味着我需要覆盖 bean 中的代码和 equal 方法吗?
  • 如果 list1 包含 bean1,list2 包含 bean2,并且 bean1 和 bean2 不引用同一个对象,那么是的,您应该重写“equals()”方法。您还应该将“hashcode()”覆盖为合理的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多